首页 > 解决方案 > 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);

标签: php

解决方案


$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
}

推荐阅读