将SQL结果转换为PHP数组

时间:2013-06-12 01:26:47

标签: php mysql arrays

我对PHP很新,我一直在环顾四周,似乎无法找到我正在寻找的具体答案。

我想创建一个SQL查询,例如:

$result = mysqli_query($connection, $command)
if (!$result) { die("Query Failed."); }

// Create my array here ... I'm thinking of maybe having to
// make a class that can hold everything I need, but I dunno    

while($row = mysqli_fetch_array($result))
{
    // Put the row into an array or class here...
}

mysqli_close($connection);

// return my array or class

基本上我想获取结果的全部内容并创建一个我可以以与行类似的方式访问的数组。例如,如果我有一个名为'uid'的字段,我希望能够通过myData ['uid']获得该字段。我想因为可能有几行,可能更像myData [0] ['uid'],myData [1] ['uid']等等。

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:18)

你可以这样做:

$rows = [];
while($row = mysqli_fetch_array($result))
{
    $rows[] = $row;
}

答案 1 :(得分:6)

您可能会尝试将mysqli_result::fetch_all()用于数组:

$result = mysqli_query($connection, $command)

if (!$result) { die("Query Failed."); }

$array = $result->fetch_all();

$result->free();

mysqli_close($connection);

注意:仅适用于MySQLND


对于课程,您可能会尝试使用以下内容:

$result = mysqli_query($connection, $command)

if (!$result) { die("Query Failed."); }

while($model = $result->fetch_assoc()){
    // Assuming ModelClass is declared
    // And have method push() to append rows.
    ModelClass::push($model);
}

$result->free();

mysqli_close($connection);

或者这个:

// Base Model - abstract model class.
class ModelClass extends BaseModel {

    // constructor
    public function __construct(mysqli &$dbms){
        // $this->dbms is MySQLi connection instance.
        $this->dbms   = &$dbms;

        // $this->models is buffer for resultset.
        $this->models = array();
    }

    // destructor
    public function __destruct(){
        unset($this->dbms, $this->models);
    }

    public function read(){            
        $result = $this->dbms->query($command);

        if($this->dbms->errno){
            throw new Exception($this->dbms->error, $this->dbms->errno);
        }

        $this->models = $result->fetch_all();

        $result->free();
    }
}

答案 2 :(得分:0)

//object oriented style mysqli
//connect to your db
$mysqli = new mysqli("host", "user", "password", "dbname");
$result = $mysqli->query("SELECT * FROM `table`");

//use mysqli->affected_rows
for ($x = 1; $x <= $mysqli->affected_rows; $x++) {
    $rows[] = $result->fetch_assoc();
}

//this will return a nested array
echo "<pre>";
print_r($rows);
echo "</pre>";

编辑它并将其放在一个类上,只要你打算用数据库进行查询就可以调用它。

答案 3 :(得分:0)

提取数组: https://www.php.net/manual/en/mysqli-result.fetch-array.php

$result = $mysqli_connection->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
            print_r($row);