Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

}
share|improve this question
up vote 45 down vote accepted

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.

share|improve this answer
9  
You're too fast man! ;) – AlienWebguy Jul 19 '11 at 1:46
    
how to put only one column in an array and index od array should be the primary key? – user1899563 Oct 8 '13 at 10:58
    
@bhawin learn how PHP arrays work and you will find it simple – alex Oct 8 '13 at 14:27

This will do the trick:

$rows = array();
$result = mysql_query("SELECT * FROM `Departments`");
while($row = mysql_fetch_assoc($result))
{
  $rows[] = $row;
}
share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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'];
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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