php + mysql 查询仅从类函数返回单行(标准类)

你能告诉我为什么这只返回我的查询的最后一行吗?正如你所看到的,我正在提取作为标准类。此外,我已经尝试了不同的方法,例如在内部使用foreach key=>值,但它没有帮助。我无法正确填充$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);


SMILET
浏览 86回答 3
3回答

精慕HU

您只需要更改这些行:$out = new stdClass;&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;while ($r = $results->fetch_object()){&nbsp; &nbsp; $out = $r;&nbsp;&nbsp;}&nbsp;对那些:$out = []; // array that will hold all the objectswhile ($r = $results->fetch_object()){&nbsp; &nbsp; array_push($out, $r);&nbsp; // add to the array the current object}&nbsp;return $out; //return the array with the objects

慕勒3428872

您将在 的每次迭代中覆盖 ,因此在返回中只有最后一个结果。您可以使用数组并追加结果(它可以是stdClass对象的数组),然后您将能够使用一个简单的循环来处理它$outwhileclass myclass {&nbsp; &nbsp; function Query($sql){&nbsp; &nbsp; &nbsp; &nbsp; $results = $this->db->query($sql);&nbsp; &nbsp; &nbsp; &nbsp; if (mysqli_num_rows($results)<1){&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; throw new Exception('NoResults');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; //copied this piece of code from @Berto99 answer from this same question&nbsp; &nbsp; &nbsp; &nbsp; $out = []; // array that will hold all the objects&nbsp; &nbsp; &nbsp; &nbsp; while ($r = $results->fetch_object()){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; array_push($out, $r);&nbsp; // add to the array the current object&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return $out; //return the array with the objects&nbsp; &nbsp; }&nbsp;&nbsp;}---------------$client = new myclass;$sql = "SELECT * FROM books";$q = $client->Query($sql);foreach($q as $resultLine){&nbsp; &nbsp; //do whatever you need to do here}

莫回无

你的$r是对象。您不需要标准类。您需要将对象添加到$out数组中。function Query($sql){&nbsp; &nbsp; $results = $this->db->query($sql);&nbsp; &nbsp; if (mysqli_num_rows($results) < 1) {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;throw new Exception('NoResults');&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp; &nbsp; $out = new stdClass;&nbsp; &nbsp; $i=0;&nbsp; &nbsp; while ($r = $results->fetch_object()){&nbsp; &nbsp; &nbsp; &nbsp; $out->{$i} = $r;&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; $i++&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; return $out;}
打开App,查看更多内容
随时随地看视频慕课网APP