MySQLi查询返回单个结果 - 应该是结果数组

时间:2012-10-07 05:16:55

标签: php mysql class mysqli prepared-statement

使用以下代码时出现问题。我已经创建了一个用于管理数据库连接的类,使用下面看到的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);
    }

}

更新

得到这个与帕特里克的帮助。能够在this question的帮助下找到以下代码,并通过一些调整,它可以很好地工作。在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;

由于代码更改,我更改了调用以解释多维数组数据,而不是单个结果。再次感谢!

1 个答案:

答案 0 :(得分:1)

Execute函数中,您正在调用$this->stmt>fetch_array()

该函数仅返回结果集的单行数组。

你可能想要:

$this->stmt->fetch_all()

<强>更新

从预准备语句中检索整个结果集:

$this->stmt->store_result()