Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SQL results into PHP array

Tags:

arrays

php

mysql

I'm fairly new to PHP and I've been looking around and can't seem to find the specific answer I'm looking for.

I want to make a SQL query, such as this:

$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

Basically I want to take the entire contents of the result and create an array that I can access in a similar fashion as the row. For example, if I have a field called 'uid' I want to be able to get that via myData['uid']. I guess since there could be several rows, maybe something more like myData[0]['uid'], myData[1]['uid'], etc.

Any help would be appreciated.

like image 363
Jonathan Plumb Avatar asked Jun 12 '13 01:06

Jonathan Plumb


People also ask

How to convert SQL query to array PHP?

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

How can we fetch data from database and store in array in PHP?

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query. You have several options to fetch data from MySQL. The most frequently used option is to use function mysql_fetch_array(). This function returns row as an associative array, a numeric array, or both.


1 Answers

You can do:

$rows = [];
while($row = mysqli_fetch_array($result))
{
    $rows[] = $row;
}
like image 195
karthikr Avatar answered Sep 30 '22 11:09

karthikr