Reputation: 321
I am populating an array from a MySQL Database, the problem is I get 9 blank fields in my dropdown box that I am trying to populate it with. What did I do wrong?
php code:
while($row = mysql_fetch_assoc($results))
{
$options[] = array(
Name => $row['Name'],
Value => $row['Value'],
ID => $row['CID']
);
}
dropdown box:
for ($i = 0; $i < 9; $i++)
{
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'
.$options[$i]["Name"].
'</option>'."\n";
}
Upvotes: 0
Views: 516
Reputation: 6548
Your quotes are backwards in your array
while($row = mysql_fetch_assoc($results))
{
$options[] = array("Name" => $row['Name'], "Value" => $row['Value'], "ID" => $row['CID']);
}
Also, using an associative array in double quotes requires you to do this:
echo "I want to print out this: {$arr['index']}";
If you don't do it this way, it (should) result in a parse error.
You might notice that this also works
echo $arr[index]
But this is not good practice because if there is a constant through a define() named index, all of your statements will use your constant's definition instead of the string you intended.
Upvotes: 2
Reputation: 77024
Assuming your query actually executes, the problem is with how you're initializing your array values to your array keys. In PHP, the keys of an associative array must be strings, and strings in PHP are quoted with single or double quotes.
$foo = array(Name => 'value'); // incorrect, Name isn't a string
$foo = array('Name' => 'value'); // correct
Accessing associative arrays also requires using strings for keys:
$foo[Name] // incorrect, Name isn't a string
$foo['Name'] // correct
When using arrays inside double quoted strings, to get their value you should surround the arrays with braces:
"$foo['Name']" // can cause problems
"{$foo['Name']}" // good practice
Note you can use the technique for braces with regular variables:
$bar = "Hello";
$foo['Name'] = "World";
echo "{$bar} {$foo['Name']}"; // prints Hello World!
If all you want to do is save all your rows, you can just store the whole $row
array:
$options[] = $row;
rather than copying each individual value from array to array. This is more concise, more readable, less error prone, and will generalize if the contents of $row
changes. Of course, if the content of $row
changes, this has the pitfall of requiring changes to things that depend on $options
.
Upvotes: 2
Reputation: 270599
You must quote the array keys Name, Value, ID
:
$options[] = array('Name' => "$row['Name']", 'Value' => "$row['Value']", 'ID' => "$row['CID']");
Placing quotes around the "$row['key']"
is unnecessary and redundant.
Upvotes: 0