I’m trying to put mysql results into an array that will look like this:
$names=array('john','bill');
Here is the code I am trying to use to do this:
$result = mysql_query("SELECT first FROM name");
$names = array ();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$names[] = $row['first'];
}
var_dump($names);
Unfortunately, it’s not returning anyhting in the results. Just an empty array. When I echo the $row[‘first’] it shows all the names so it’s just not putting them in the array. Can anyone see what I am doing wrong?
There is nothing wrong with that code. Ran similar query with some test data and the array gets populated just fine. The space after the array keyword does not matter. Here is the code I ran:
mysql_connect('localhost', 'test_user', 'test');
mysql_select_db('test_db');
$result = mysql_query("SELECT fruit FROM fruits");
$test = array ();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$test[] = $row['fruit'];
}
var_dump($test);