3

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()) {
    // ...
}

3 Answers 3

15

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

work like a charm thx! so my mistake is assuming execute() returned result right? so I need to use get_result(). is get_result() same as query()?
no its replacement for binding result step. else you should do a bind_result i guess.
what is get_result() do? I got the same result returned by $result = $db->query($query).. why??
0

$stmt->execute(); doesn't return result. You need $stmt->get_result();.

You can rewrite your code like this:

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

Comments

-1

replace this:

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

by this

  $stmt->bind_result($category_id);

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

2 Comments

but mithunsatheesh method is working, can please explain more?
both ways are right, my way you're binding the result of stmt to a variable, then fetching stmt and using the variable you binded to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.