MySQL Array to PHP Array

We saw in our MySQL Fetch Array Tutorial how to retrieve data from a MySQL database using PHP. This post is similar but will focus on converting the array that is returned from MySQL to a PHP array.

This technique is important as it allows us to convert data to a format that we can directly work on using PHP.

For the following examples, once again, we will assume that we have a database called "employees" and it contains an "employees" table as follows:

first_name last_name
Paul Pitterson
Francine Beecham
Raul DiNozzo

To store what is returned from MySQL as a PHP array we can use code similar to the one below:

<?php
 
// connect and execute query
$connection = mysql_connect("localhost", "mysqluser", "foobar"); 
mysql_select_db("employees");
$sql = "SELECT first_name FROM employees";
$result = mysql_query($sql);
 
$count = 0; // set a counter variable to zero
$employee_array = null; // this is our empty PHP array
 
while ($row = mysql_fetch_array($result)) // iterate through array
{
  // store results from mysql in our own PHP array
  $employee_array[$count] = $row['first_name'];
 
  // increment counter
  $count++;
}
 
mysql_close($connection);
 
// we can now iterate through our own array to retrieve the data
for ($i = 0; $i < count($employee_array); $i++)
  echo $employee_array[$i] . '<br />';
 
?>

The result would be:

Paul
Francine
Raul

The idea here is to store the data from the array returned from MySQL in our own array at the same time when we are using the mysql_fetch_array function. After we have the stored it in our own array we can then process it later without using a MySQL function.

Note how we used a while loop to retrieve the data from the result of the MySQL query. This was because we did not know beforehand how many rows would be returned. On the other hand, when we are outputting the data, we can use the count function to find out the PHP array size. This means that we can now use a for loop instead of the while loop we had earlier to process the new array.

We hope you found this tutorial useful. Please consider linking to it if you like it.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...