I'm using a prepared statement to SELECT *
from a MySQL table and I'm not sure how to use while($row = mysqli_fetch_array($stmt))
to loop through and select items from the result array. This is my code, what am I doing wrong?
$link = mysqli_connect($host, $username, $password, $db);
$query = "SELECT * from `wp_posts` WHERE ID=? ";
//$result = mysqli_query($link, $query);
$stmt = mysqli_prepare($link, $query);
if($stmt){
mysqli_stmt_bind_param($stmt, "i", $pid);
mysqli_stmt_bind_result($stmt, $dbpid);
mysqli_stmt_execute($stmt);
mysqli_stmt_fetch($stmt);
}
while($row = mysqli_fetch_array($stmt)){
?>
<h2 align="center"> <?php echo $row['post_title']; ?> </h2><br>
<div class="paracenter">
<p id="cont"><?php echo $row['post_content']; ?></p>
<hr color="black" width="10%">
</div>
<?php } ?>
Dunno if anyone will be interested in the proper answer for this already answered and accepted question, but what the heck.
To answer your question using mysqli, you have to use get_result().
So, the proper mysqli-based solution will be
and then you can use $data in the foreach loop for the output as it showed in the other answer.
While for PDO the proper code would be as follows, and it's indeed lighter.
and then you can use $stmt in the foreach loop for the output as it showed in the other answer.
You don't use
bind_result()
withfetch_array()
. You either make repeated calls tofetch()
to read the columns into the individual variables bound withbind_result()
OR don't usebind_result()
, callmysqli_smt_get_result()
to pull the results into amysqli_result
object, and make repeated calls tomysqli_fetch_array()
to load the row into your$row
array.Since you're using
SELECT *
, the unbound-result approach would be more logical. For your code:Just for comparison, here's how you would use
bind_result()
(and also how to use the object syntax):Note that when using
bind_result()
your result values are returned as individual scalars rather than in an array, and that you need to bind the result variables to the columns in order, so you need to know what columns are in the result.Hope that helps.
Nothing wrong with Darwin's answer, but wanted to point out PDO as an alternative with much lighter syntax:
No need for any binding at all, and personally I find it much easier to work with.