3

I am trying to store the data from my sql database into an array. Currently I have this:

$query = mysql_query("SELECT * FROM  `InspEmail` WHERE  `Company` LIKE  '$company'");

while($row = mysql_fetch_array($query))
    {

        $inspector = $row['name'];

    }

The problem is that I have 8 rows of data. I need to store each 8 names from that database into an array. When I try this:

$inspector = array($row['name']);

It doesn't work.

1
  • 1
    Thank you for all the great answers!! Works perfectly now :) Commented May 17, 2011 at 17:35

5 Answers 5

5

If you want to store all of the names in an array, you need to define the array outside the scope of the while loop and append to it. Like this:

$nameArray = array();
while($row = mysql_fetch_array($query)) {
    // Append to the array
    $nameArray[] = $row['name'];   
}
Sign up to request clarification or add additional context in comments.

3 Comments

technically you don't have to define it outside the loop. However, I am always a fan of declaring variables so you can document them.
You're right! I often forget php lets you append to an uninitialized array.
It actually throws a notice. though most have notices turned off.
3

What you want is:

$inspector[] = $row['name'];

This will store all 8 names in an array similar to:

array(
     [0] => name1
     [1] => name2
     [2] => name3

)

Comments

2

Lots of good answers. But if you do this often, you might want to write a little function:

mysql_field_array($sql, $fieldname)
{
    $res = mysql_query($sql);
    $a = array();
    while($row = mysql_fetch_array($res))
    {
        $a[] = $row[$fieldname];
    }
    mysql_free_result($res);
    return $a;
}

Comments

0

Replace this line...

$inspector = $row['name'];

...with this:

$inspector [] = $row['name'];

After that, the inspector array contains all the names.

Comments

0
$query = mysql_query("SELECT * FROM  `InspEmail` WHERE  `Company` LIKE  '$company'");
$data = array();
while($row = mysql_fetch_array($query))
{
    $inspector[] = $row;
}
for($i=0;$i<mysql_num_rows($row);$i++)
{
  $data = $inspector[$i];
}
return $data;

Check it...

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.