問題描述
我正在從 mysql 遷移到 mysqli,但在查詢中從數(shù)據(jù)庫(kù)返回多于一行時(shí)遇到問題.
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)建一個(gè)函數(shù),我可以在其中查詢數(shù)據(jù)庫(kù)并以關(guān)聯(lián)數(shù)組或?qū)ο蟮男问椒祷亟Y(jié)果.我做錯(cuò)了什么?
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查詢只返回第一行的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!