簡體   English   中英

MySQLi查詢返回單個結果—應該是結果數組

[英]MySQLi Query Returning Single Result — Should Be Array of Results

以下代碼有些麻煩。 我創建了一個用於管理數據庫連接的類,使用下面顯示的queryPreparedQuery進行操作,並且在獲取單個用戶的數據或使用此類方法返回單個結果的任何數據時都能正常工作...

include 'stuff/class_stuff.php';

function SweetStuff() {

    $foo = new db_connection();
    $foo->queryPreparedQuery("SELECT Bacon, Eggs, Coffee FROM Necessary_Items WHERE Available = ?",$bool);
    $bar = $foo->Load();
    $stuff = 'Brand of Pork is '.$bar['Bacon'].' combined with '.$bar['Eggs'].' eggs and '.$bar['Coffee'].' nectar for energy and heart failure.';

    return $stuff;

}

echo SweetStuff();

問題是,我想在此處構建功能以允許MySQL查詢返回多個結果。 我想念什么? 我知道它正盯着我...

class db_connection
{
    private $conn;
    private $stmt;
    private $result;

    #Build a mysql connection
    public function __construct($host="HOST", $user="USER", $pass="PASS", $db="DB_NAME")
    {
        $this->conn = new mysqli($host, $user, $pass, $db);

        if(mysqli_connect_errno())
        {
            echo("Database connect Error : "
            . mysqli_connect_error());
        }
    }
    #return the connected connection
    public function getConnect()
    {
        return $this->conn;
    }
    #execute a prepared query without selecting
    public function execPreparedQuery($query, $params_r)
    {
        $stmt =  $this->conn->stmt_init();
        if (!$stmt->prepare($query))
        {
            echo("Error in $statement when preparing: "
            . mysqli_error($this->conn));
            return 0;
        }
        $types = '';
        $values = '';
        $index = 0;
        if(!is_array($params_r))
        $params_r = array($params_r);
        $bindParam = '$stmt->bind_param("';
        foreach($params_r as $param)
        {

            if (is_numeric($param)) {
                $types.="i";
            }
            elseif (is_float($param)) {
                $types.="d";
            }else{
                $types.="s";
            }
            $values .=  '$params_r[' . $index . '],';
            $index++;
        }
        $values = rtrim($values, ',');
        $bindParam .= $types . '", ' . $values . ');';      

        if (strlen($types) > 0)
        {
            //for debug
            //if(strpos($query, "INSERT") > 0)
            //var_dump($params_r);
            eval($bindParam);
        }

        $stmt->execute();       
        return $stmt;
    }
    #execute a prepared query
    public function queryPreparedQuery($query, $params_r)
    {
        $this->stmt = $this->execPreparedQuery($query, $params_r);
        $this->stmt->store_result();
        $meta = $this->stmt->result_metadata();
        $bindResult = '$this->stmt->bind_result(';
        while ($columnName = $meta->fetch_field()) {
            $bindResult .= '$this->result["'.$columnName->name.'"],';
        }
        $bindResult = rtrim($bindResult, ',') . ');';
        eval($bindResult);
    }
    #Load result
    public function Load(&$result = null)
    {       
        if (func_num_args() == 0)
        {
            $this->stmt->fetch();
            return $this->result;
        }
        else
        {
            $res = $this->stmt->fetch();
            $result = $this->result;
            return $res;
        }
    }

    #Load result
    public function Execute(&$result = null)
    {       
        if (func_num_args() == 0)
        {
            $this->stmt->fetch_array();
            return $this->result;
        }
        else
        {
            $res = $this->stmt->fetch_array();
            $result = $this->result;
            return $res;
        }
    }   

    private function bindParameters(&$obj, &$bind_params_r)
    {
        call_user_func_array(array($obj, "bind_param"), $bind_params_r);
    }

}

更新

在Patrick的幫助下進行了此操作。 借助此問題 ,可以找到以下代碼,並且進行了一些調整,使其工作精美。 在ExecPreparedQuery中的execute()語句之后添加了以下內容,在最后返回一個數組,而不是單個結果:

    # these lines of code below return multi-dimentional/ nested array, similar to mysqli::fetch_all()
    $stmt->store_result();

    $variables = array();
    $data = array();
    $meta = $stmt->result_metadata();

    while($field = $meta->fetch_field())
        $variables[] = &$data[$field->name]; // pass by reference

    call_user_func_array(array($stmt, 'bind_result'), $variables);

    $i=0;
    while($stmt->fetch())
    {
        $array[$i] = array();
        foreach($data as $k=>$v)
            $array[$i][$k] = $v;
        $i++;
    }

    # close statement
    $stmt->close();

    return $array;

由於更改了代碼,因此我當然更改了解釋多維數組數據而不是單個結果的調用。 再次感謝!

在您的Execute函數中,您正在調用$this->stmt>fetch_array()

該函數僅返回結果集單行的數組。

您可能想要:

$this->stmt->fetch_all()

更新資料

要從准備好的語句中檢索整個結果集:

$this->stmt->store_result()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM