繁体   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