本文介紹了mysqli查詢只返回第一行的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在從 mysql 遷移到 mysqli,但在查詢中從數(shù)據(jù)庫返回多于一行時遇到問題.
I am migrating from mysql to mysqli, and I am having trouble returning more than one row from the database in a query.
$db = new mysqli($hostname, $sql_us, $sql_us_pwd, $sql_db); // This is already connected
function db_query($db, $query, $type = 'object') {
global $db;
$result = $db->query($query);
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
return $row;
}
} else {
while($row = $result->fetch_object()) {
return $row;
}
}
mysqli_free_result($result);
}
$query = "SELECT * FROM `users`";
$user = db_query($db, $query);
print_r($user); // This is only returning the first row of results
我顯然是在嘗試創(chuàng)建一個函數(shù),我可以在其中查詢數(shù)據(jù)庫并以關(guān)聯(lián)數(shù)組或?qū)ο蟮男问椒祷亟Y(jié)果.我做錯了什么?
I'm obviously trying to make a function where I can query the database and either return the results in an associative array or as an object. What am I doing wrong?
推薦答案
使用此代碼:
$rows = array();
if ($type == 'assoc') {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
while($row = $result->fetch_object()) {
$rows[] = $row;
}
}
return $rows;
您在 while 內(nèi)使用 return 并在第一次迭代后 return 終止 while 循環(huán),這就是為什么您只得到一行.
You are using the return inside the while and return terminates the while loop after first iteration that's why you are getting only one row.
這篇關(guān)于mysqli查詢只返回第一行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!