2

I am trying to get rows from the database using MySQl prepared statements and get result. However this is not working.

Please can someone see where I am going wrong? I have been trying solutions for hours but I can't get it to work. The page just doesn't load as if the query has failed.

 $tag = trim($_GET['tag']);

 $stmt = $mysqli->prepare('SELECT posts.* FROM tags JOIN posts ON posts.id = tags.post_id WHERE tag = ?');
 $stmt->bind_param('s', $tag);
 $stmt->execute();
 $stmt->store_result();
 $result = $stmt->get_result();

 while ($row = $result->fetch_assoc()) {

     echo $row['tag'];

 }      

 $stmt->free_result();
 $stmt->close();
2
  • Have you checked that your query is getting results? Commented Oct 4, 2014 at 20:58
  • Yes it is returning 4 rows Commented Oct 4, 2014 at 21:42

1 Answer 1

1

Try this:

$stmt = $mysqli->prepare('SELECT posts.id FROM tags JOIN posts ON posts.id = tags.post_id WHERE tag = ?');

...

$stmt->bind_result($id);    

while ($stmt->fetch()) {

    // var_dump entire row to ensure the key you expect is avail
    var_dump($id);

}

Upate

If you want to do a select *, vs having to specify EVERY column individually, check out this post (not the accepted answer, but the highest scoring answer). Otherwise I strongly urge you to check out PDO, as it makes these basic read ops much easier.

Sign up to request clarification or add additional context in comments.

4 Comments

Notice the correction, should be $stmt in the while loop, not $result
The query now does return results. However nothing comes out in the var_dump function
Ok, corrected code, you are using mysqli api, which you should consider as deprecated, and use PDO instead. Notice in the query you have to specify the column you are selecting, so you can correctly bind the result after. More info @ us2.php.net/manual/en/mysqli-stmt.bind-result.php
That works now, thank you! Would there be a way to achieve this using $stmt->get_result() though incase I needed to search posts.* to gather all variables?

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.