Help with this array?

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?

I was tempted to use lmgtfy… :smile:

http://stackoverflow.com/questions/6524116/sql-results-as-php-array

HTH,

:slight_smile:

Remove the space.

array()

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

and results:

array (size=5)
  0 => string 'orange' (length=6)
  1 => string 'apple' (length=5)
  2 => string 'banana' (length=6)
  3 => string 'grape' (length=5)
  4 => string 'mandarin' (length=8)

Code is ok. Show your table structure, maybe there is a just typo in your query

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.