【问题标题】:mysqli prepared statement with while loopmysqli用while循环准备语句
【发布时间】:2015-03-23 15:26:16
【问题描述】:

我正在尝试使用 mysqli 进行非常简单的查询。快把我逼疯了!

我只希望$data 是来自 sql 查询的值的数组。

这是我的代码...

$req = $app->request();
$hashtag = $req->get('hashtag');

require_once 'Slim/lib/database.php';

$db = connect_db();

$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = '%#' . $hashtag . '%';
$statement -> bind_param("s", $newhashtag);

$statement -> execute();

$statement -> bind_result($result);

while ( $row = mysqli_fetch_array($statement) ) {
    $data[] = $row;
}

print_r($data);

$statement -> close();

我只是收到一个错误mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given,在fetch_array 上使用$result$statement 并没有什么不同

【问题讨论】:

  • 当你已经拥有$statement->bind_result($result)时为什么还要使用while循环

标签: php mysql mysqli


【解决方案1】:

你可以试试这个:

$statement = $db->prepare("SELECT `content` FROM `posts` WHERE `content` LIKE ?");
$newhashtag = "%#$hashtag%";
$statement->bind_param("s", $newhashtag);
$statement->execute();
$result = $statement->get_result();

while ($row = $result->fetch_assoc())
{
    $data[] = $row;
}

这使用get_result() function,用于从准备好的语句中获取结果。

这是在 while 循环之外初始化并分配给一个新变量,在本例中为 $result
然后将$result->fetch_assoc() 分配给$row 并且可以在循环内访问。将每一列作为数组中的键访问,这样$row["content"] 将返回该列下每一行的内容

【讨论】:

    【解决方案2】:

    要从准备好的语句中获取结果对象,您可以使用get_result()。然后可以使用foreach 循环迭代此对象。

    $statement->execute();
    
    $result = $statement->get_result();
    
    foreach ($result as $row) {
        print_r($row);
    }
    

    如果需要将所有行提取到数组中,可以使用fetch_all()

    $statement->execute();
    
    $result = $statement->get_result();
    
    $data = $result->fetch_all(MYSQLI_ASSOC);
    print_r($data);
    

    您还可以通过将每列绑定到一个变量来获取数据。首先,使用bind_result() 指定要填充的变量,然后调用fetch() 来填充该变量。

    $statement->execute();
    
    $statement->bind_result($content);
    
    while ( $statement->fetch() ) {
        // Every time fetch is called a value from the next row will be inserted into $content
        $data[] = $content;
    }
    
    print_r($data);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2014-11-14
      • 2012-04-04
      • 2011-07-01
      相关资源
      最近更新 更多