問題描述
這是我在 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 中存儲和迭代查詢結果的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!