mysqli prepared statement with while loop

≯℡__Kan透↙ 提交于 2021-01-29 17:18:16

问题


I am trying to do an extremely simple query using mysqli. It is driving me mad!

I just want $data to be an array of the values from the sql query.

This is my code...

$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();

I just get an error mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given and it doesn't make a difference using $result or $statement on the fetch_array


回答1:


replace these lines:

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

with these:

while ($row = $statement->fetch()) {
   $data[] = $row;
}



回答2:


For anyone coming across this question and finding that the accepted solution does not work (it didn't for me).

Then try this:

$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;
}

This uses the get_result() function, which is used to get the result from a prepared statement.

This is initialised outside the while loop and assigned to a new variable, in this instance $result.
Then $result->fetch_assoc() is assigned to $row and can be accessed within the loop. Accessing each column as a key from the array such that $row["content"] would return the content from each row under that column



来源:https://stackoverflow.com/questions/29214066/mysqli-prepared-statement-with-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!