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

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

问题描述

这是我在phpi中使用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.

现在,在一段时间内,我想使用$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.

NB :我想避免使用multi_query().

推荐答案

我已经解决了这个问题:

I have solved the problem:

$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天全站免登陆