tiger_groove
tiger_groove

Reputation: 1016

PHP storing a two dimension array from MySQL query

I have a simple question. I have an array that has two columns (id, name) that is a result of a MySQL query. I want to store the result of the query into a array variable so i can access each element when i need to.

I am able to store a one dimension array like the following:

    $array = array();
    while($row = mysqli_fetch_assoc($result))
    {
        $array[] = $row['name'];
    }

How can I store and access a two dimensional array? Also is it best to use a for loop or while loop to store these?

Upvotes: 0

Views: 252

Answers (2)

kyle
kyle

Reputation: 2638

Don't specifically store the index of $row but rather store the whole row.

$array = array();
while($row = mysqli_fetch_assoc($result))
{
    $array[] = $row;
}

Then $array will have the following structure:

$array = [
    [
       'id'=> ...,
       'name' => ...,
    ],
    ...
];

To initially access all of the results from [mysqli_fetch_assoc][1] you will want to use the while loop like you are, mysqli_fetch_assoc will continue to output results until it doesn't have any more data. Then at that point mysqli_fetch_assoc will return NULL. This will signal to your while loop to stop iterating.

Then to access variables inside of your $array, I recommend using foreach.

You could then do:

foreach ($array as $row) {
  do something with $row['name'] or $row['id']
}

You could also use a for loop, but it takes more work IMO. Compare the above with this alternative:

for ($i = 0; $i < count($array); $i++) {
   $row = $array[$i];
   do something with $row['name'] or $row['id']
}

Upvotes: 1

Henry
Henry

Reputation: 7891

Simply do this:

$array = array();
while($row = mysqli_fetch_assoc($result))
{
    $array[] = $row;
}

To access your results you can do this:

$firstResultRow = $array[0];
$firstResultName = $array[0]['id'];
$firstResultName = $array[0]['name'];

This will tell you if a particular row exists:

if(isset($array[$x])) {
    $aRow = $row[$x];
    // do stuff with $aRow;
}

This will give you a row count for your array:

$rowCount = count($array);

This will set up a loop through your array:

foreach($array as $index => $row) {
    $id = $row['id']
    $name = $row['name'];
    // $index will have the array index of the current row. 0 -> $rowCount - 1
}

Upvotes: 1

Related Questions