26

If I am fetching data from a MySQL database and using a while loop to iterate through the data how would I add each one to array?

$result = mysql_query("SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{

}

5 Answers 5

76

Build an array up as you iterate with the while loop.

$result = mysql_query("SELECT * FROM `Departments`");
$results = array();
while($row = mysql_fetch_assoc($result))
{
   $results[] = $row;
}

Alternatively, if you used PDO, you could do this automatically.

2
  • how to put only one column in an array and index od array should be the primary key?
    – user1899563
    Oct 8, 2013 at 10:58
  • @bhawin learn how PHP arrays work and you will find it simple
    – alex
    Oct 8, 2013 at 14:27
7

This will do the trick:

$rows = array();
$result = mysql_query("SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{
  $rows[] = $row;
}
6

This has been one of the fastest ways for me to create (multi-dimensional) arrays. I'm not sure if you want all of your results smooshed into one array or not.

// Read records
$query = "SELECT * FROM `Departments`"; 
$query = mysql_query($query);

// Put them in array
for($i = 0; $array[$i] = mysql_fetch_assoc($query); $i++) ;

// Delete last empty one
array_pop($array);

You can use print_r($array) to see the results.

2

my fav is the following;

$result=odbc_exec($conn,$sql);
if ($result) {
    while($found_results[] = odbc_fetch_array($result)) { } 
    array_pop($found_results); //pop off the empty line from while loading
}

you dont need to pop the last line, but it does leave a blank if you omit it. works the same for mysql obviously.

2

If you have multiple columns in your Departments table and you want to save in different array.

$result = mysql_query("SELECT * FROM `Departments`");
$dept_id = array();
$dept_name=array();
while($row = mysql_fetch_assoc($result))
{
//fetches and store all results in id column on your departments table
$dept_id= $row['id'];
//fetches and store all results in name column on your departments table    
$dept_name=$row['name'];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.