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();
David
  • 35
  • 4

1 Answers1

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.

Community
  • 1
  • 1
Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
  • Notice the correction, should be `$stmt` in the while loop, not `$result` – Mike Purcell Oct 04 '14 at 21:53
  • The query now does return results. However nothing comes out in the `var_dump` function – David Oct 04 '14 at 21:59
  • 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 @ http://us2.php.net/manual/en/mysqli-stmt.bind-result.php – Mike Purcell Oct 04 '14 at 22:12
  • 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? – David Oct 05 '14 at 09:16