While loop PHP get_result not working

删除回忆录丶 提交于 2019-12-02 05:28:23

问题


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();

回答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.



来源:https://stackoverflow.com/questions/26197031/while-loop-php-get-result-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!