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.
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'];
}
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
)
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;
}
Replace this line...
$inspector = $row['name'];
...with this:
$inspector [] = $row['name'];
After that, the inspector array contains all the names.
$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...
精彩评论