3 回答

TA貢獻1845條經(jīng)驗 獲得超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條經(jīng)驗 獲得超6個贊
您將在 的每次迭代中覆蓋 ,因此在返回中只有最后一個結果。您可以使用數(shù)組并追加結果(它可以是stdClass對象的數(shù)組),然后您將能夠使用一個簡單的循環(huán)來處理它$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條經(jīng)驗 獲得超7個贊
你的$r是對象。您不需要標準類。您需要將對象添加到$out數(shù)組中。
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 關注
- 110 瀏覽
添加回答
舉報