Jump to content

[SOLVED] Selecting the correct variable for a pulldown menu


tqla

Recommended Posts

Hello. I've been at this for an hour and I can't figure it out. Hope someone can help me.

 

I have created the following script to pull from my DB. My ultimate goal is to use the "id" and "title" field to populate the pulldown menu.

 

<?php
include('includes/connnection.inc.php');
$sql2 = 'SELECT * FROM category ORDER BY title ASC';
$result2 = mysql_query($sql2) or die(mysql_error());
while($row2 = mysql_fetch_assoc($result2))
{
$rows[] = $row2;
}

   echo '<pre>';
   print_r($rows);
   echo '</pre>';


print '<select name="category">';
foreach ($rows as $key => $value)
{
print "\n<option value=\"$key\"> $value</option>";
}
print '</select>';

?>

 

the "print-r" function is just so I can see my array. It looks like this

 

Array
(
    [0] => Array
        (
            [id] => 1
            [title] => About Us
        )

    [1] => Array
        (
            [id] => 4
            [title] => Contact Us
        )

    [2] => Array
        (
            [id] => 3
            [title] => Products
        )

    [3] => Array
        (
            [id] => 2
            [title] => Services
        )

)

 

It appears to be a multidimensional array so my dropdown menu's source code looks like this:

 

<select name="category">
<option value="0"> Array</option>
<option value="1"> Array</option>
<option value="2"> Array</option>
<option value="3"> Array</option></select>

 

You see the problem? The key is of the key of each Array and the value is "Array". What I want is the key to be the "id" and the value to be the "title" like the "print-r" read out. For example:

 

<select name="category">
<option value="1"> About Us</option>
<option value="4"> Contact Us</option>
<option value="3"> Products</option>
<option value="2"> Services</option></select>

 

Can someone help out. Thanks.  ???

Opalelement! I kept thinking about what you said and it hit me. It's working now. I had to change my query to "mysql_fetch_array" and rewrite the script a lil bit. Awesome.

 

<?php
include('includes/connnection.inc.php');
$sql2 = 'SELECT * FROM category ORDER BY title ASC';
$result2 = mysql_query($sql2) or die(mysql_error());

print '<select name="category">';
while($row2 = mysql_fetch_array($result2))
{
$title = $row2['title'];

print "\n<option value=\"$title\">$title</option>";
}
print '</select>';

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.