14

我对 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

4 回答 4

21

你可以做:

$rows = [];
while($row = mysqli_fetch_array($result))
{
    $rows[] = $row;
}
于 2013-06-12T01:29:23.150 回答
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();
    }
}
于 2013-06-12T01:32:26.310 回答
1
//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>";

编辑它并将其放在一个类中,只要您要使用数据库进行查询,就可以随时调用它。

于 2013-06-12T02:10:03.793 回答
1

fetch_array: 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);
于 2020-10-28T09:12:31.657 回答