Convert SQL results into PHP array

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);

//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>";

edit this and put it on a class and just call it anytime you're going to make a query with your database.


You can do:

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

You might try to use mysqli_result::fetch_all() for arrays:

$result = mysqli_query($connection, $command)

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

$array = $result->fetch_all();

$result->free();

mysqli_close($connection);

NOTE: This works with MySQLND only.


For class, you might try to use something like this:

$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);

OR this:

// 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();
    }
}

Tags:

Mysql

Php

Arrays