虽然循环 PHP get_result 不起作用

时间:2023-04-08
本文介绍了虽然循环 PHP get_result 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试使用 MySQl 准备好的语句从数据库中获取行并获得结果.然而,这是行不通的.

请有人知道我哪里出错了吗?我已经尝试了几个小时的解决方案,但我无法让它发挥作用.该页面不会加载,就好像查询失败一样.

 $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()) {回声 $row['tag'];}$stmt->free_result();$stmt->close();

解决方案

试试这个:

$stmt = $mysqli->prepare('SELECT posts.id FROM tags JOIN posts ON posts.id = tags.post_id WHERE tag = ?');...$stmt->bind_result($id);而 ($stmt-> fetch()) {//var_dump 整行以确保您期望的密钥可用var_dump($id);}

更新

如果你想做一个选择 *,而不是单独指定每一列,看看这个 post(不是接受的答案,而是得分最高的答案).否则,我强烈建议您查看 PDO,因为它使这些基本的读取操作变得更加容易.>

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

解决方案

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.

这篇关于虽然循环 PHP get_result 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:对来自 while 循环的记录进行分组 |PHP 下一篇:在 MySQL 服务器上使用 PHP 进行循环

相关文章