mysqli query only returning first row(mysqli查询只返回第一行)
问题描述
我正在从 mysql 迁移到 mysqli,但在查询中从数据库返回多于一行时遇到问题.
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
我显然是在尝试创建一个函数,我可以在其中查询数据库并以关联数组或对象的形式返回结果.我做错了什么?
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 内使用 return 并在第一次迭代后 return 终止 while 循环,这就是为什么您只得到一行.
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.
这篇关于mysqli查询只返回第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:mysqli查询只返回第一行


- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- Laravel 仓库 2022-01-01