3 回答
TA贡献1845条经验 获得超8个赞
您只需要更改这些行:
$out = new stdClass;
while ($r = $results->fetch_object()){
$out = $r;
}
对那些:
$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
TA贡献1848条经验 获得超6个赞
您将在 的每次迭代中覆盖 ,因此在返回中只有最后一个结果。您可以使用数组并追加结果(它可以是stdClass对象的数组),然后您将能够使用一个简单的循环来处理它$outwhile
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
}
TA贡献1865条经验 获得超7个赞
你的$r是对象。您不需要标准类。您需要将对象添加到$out数组中。
function Query($sql)
{
$results = $this->db->query($sql);
if (mysqli_num_rows($results) < 1) {
throw new Exception('NoResults');
}
$out = new stdClass;
$i=0;
while ($r = $results->fetch_object()){
$out->{$i} = $r;
$i++
}
return $out;
}
- 3 回答
- 0 关注
- 85 浏览
添加回答
举报