SELECT statement with fetch_array in mysqli prepar

2020-01-27 07:33发布

问题:

I always find it difficult to write MySQLi prepared statements, because many functions work differently than in the old way. Right now I am facing a problem regarding fetch_array().

$stmt = $db->prepare("SELECT category_id FROM post_items Where user_id = ?");
$stmt->bind_param('i', $userid);
$result = $stmt->execute();
while ($row = $result->fetch_array()) {
    // ...
}

回答1:

you are trying to fetch the results by

$result = $stmt->execute();

which is not the case. as execute will return you only a boolean value.

do it like.

$stmt = $db->prepare("SELECT category_id FROM post_items Where user_id = ?");
$stmt->bind_param('i', $userid);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
        //result is in row
}


回答2:

replace this:

    $result = $stmt->execute();
    while ($row = $result->fetch_array()) {

by this

  $stmt->bind_result($category_id);

  while($stmt->fetch()){
       $myArray=$category_id;
  }


标签: php mysql mysqli