在 mysqli 中存储和迭代查询结果 [英] Store and iterate over result of query in mysqli

查看:24
本文介绍了在 mysqli 中存储和迭代查询结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 php 中的简单查询,使用 mysqli 面向对象的风格:

This is my simple query in php, using mysqli object oriented style:

$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
$stmt->bind_result($name);

while($stmt->fetch()){
   echo $name." ";
}

$stmt->free_result();
$stmt->close();

这很好用.我获得了从 select 语句中检索到的名称列表.

This works fine. I obtain the list of name retrieved from the select statement.

现在,在 while 我想使用 $name 变量作为另一个查询的参数,但 mysqli 不允许这样做,因为我必须关闭第一个查询,然后调用第二个查询.

Now, inside the while I want use the $name variable as parameter for another query, but mysqli do not allow this, since I have to close the first query and then call the second query.

所以我想我必须存储第一个查询的结果,然后调用新查询来迭代结果.

So I think I have to store the result of the first query and then iterate over the result calling a new query.

我尝试了以下方法:

$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
//$stmt->bind_result($name);
$result = $stmt->store_result();
$stmt->free_result();
$stmt->close();

while ($row = $result->fetch_row()) 
{
    echo $row[0]." ";
}

但这行不通.while 中的代码永远无法访问.

But this does not work. The code inside while is never reached.

注意:我想避免使用 multi_query().

推荐答案

我已经解决了问题:

$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
$result = $stmt->get_result();
$stmt->free_result();
$stmt->close();

while ($row = $result->fetch_array(MYSQLI_NUM)) 
{
    echo $row[0]." ";
}

只需使用 get_result()fetch_array()

这篇关于在 mysqli 中存储和迭代查询结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆