Using PHP and MySQL to populate form options

software development

#1

I’m super green at Database usage and fairly inexperienced at PHP, so I apologize if my question seems really dumb…

Basically I’ve built a database and table and populated the columns with values I need. However, it’s not working. Could someone please double check my work and tell me if they see any blaring discrepancies?

I’m using the values of the user table to populate a pulldown menu, or I’d like to be:

            [code]<select>
                <option>Select a User (Required Field)</option>
                <?php
                    $user_name = "DATABASE_USER";
                    $password = "TOPSECRET_PASSWORD";
                    $database = "DATABASE_NAME";
                    $server = "SERVER_NAME";
                    //connect to host
                    $db_handle = mysql_connect($server,$user_name,$password);
                    if (!$db_handle){
                        die('Could not connect: ' . mysql_error());
                    }
                    //connect to database
                    mysql_select_db($database, $db_handle);
                    //collect user names
                    $query = mysql_query("SELECT * FROM user") 
                        or die(mysql_error());
                    $row_count = mysql_num_rows($query);
                    for ($i=0; $i<$row_count; $i++) {
                        $user = mysql_fetch_array($query);
                        echo("<option value=\"".$user['name']."\">".$user['name']."</option>");
                    }
                    mysql_close($db_handle);
                ?>
            </select>[/code]

THANK YOU FOR YOUR HELP!!!


#2

Do not rely on mysql_num_rows() returning a useful value for SELECT queries. It’s only meant to return the number of modified rows after an INSERT/REPLACE, UPDATE, or DELETE query.

To loop over a result set, do this:

$query = mysql_query("...");
while($row = mysql_fetch_array($query)) {
    do stuff with $row;
}

#3
while($user = mysql_fetch_array($query)) {
    echo("<option value=\"".$user['name']."\">".$user['name']."</option>");
}

Actually, I had it this way first. I’ve tried the syntax like 3 different ways with no success. I’ve tried troubleshooting this thing from all kinds of angles. That’s what led me to think my User’s settings might have been off.