php - php + mysql 查询仅从类函数返回单行(std 类)
问题描述
你能告诉我为什么这只返回我查询的最后一行吗?如您所见,我正在提取为 std 类。此外,我已经尝试了不同的方法,例如 foreach key=>value 在 while 内,但它没有帮助。我无法正确填充 $out。
class myclass {
function Query($sql){
$results = $this->db->query($sql);
if (mysqli_num_rows($results)<1){
throw new Exception('NoResults');
}
$out = new stdClass;
while ($r = $results->fetch_object()){
$out = $r;
}
return $out;
$out = null;
}
}
}
---------------
$client = new myclass;
$sql = "SELECT * FROM books";
$q = $client->Query($sql);
print_r($q);
解决方案
您$out
在 的每次迭代中都会覆盖while
,因此您将只有最后一个结果在返回中。您可以使用一个数组并附加结果(它可以是一个 stdClass 对象的数组),然后您就可以通过一个简单的循环来使用它
class myclass {
function Query($sql){
$results = $this->db->query($sql);
if (mysqli_num_rows($results)<1){
throw new Exception('NoResults');
}
//copied this piece of code from @Berto99 answer from this same question
$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
array_push($out, $r); // add to the array the current object
}
return $out; //return the array with the objects
}
}
---------------
$client = new myclass;
$sql = "SELECT * FROM books";
$q = $client->Query($sql);
foreach($q as $resultLine){
//do whatever you need to do here
}
推荐阅读
- ruby-on-rails - 使 capistrano 修订文件可公开访问
- visual-studio-code - Visual Studio Code - 活动栏中的图标已消失
- css - CSS 剪辑:未设置;在 Safari 上
- c# - ADODB 语句的执行突然停止
- sql - Jenkins - 使用“;”将 sql 查询结果转换为字符串 作为分隔符
- postgresql - 使用 Slick 3.2.2 在 PostgreSQL 中插入一行
- c++ - cmake 将 clang-cl 检测为 clang
- c# - out var,当前上下文中不存在名称“var”
- android - Gif 未在某些 Nougat 版本上显示
- azure-devops - VSTS 发布 API 文档