colafran Posted March 13, 2008 Share Posted March 13, 2008 I am new to PHP, bear with me I am looking to populate a drop down list by doing a MySQL query using PHP. I found a code example, but it does not seem to work, can anyone tell me if there is something wrong with it? The posting I saw was from 2005, so I am wondering if the code is incompatible with PHP5? Before you ask, I know that my database query is working, I cut and pasted it from another script that is working. Another thing, the drop down does show 5 spaces, which it should be because the sql query is returning only 5 records, but the spaces are blank. This is the exact code I have: <?php // Connect and select a database mysql_connect("localhost", "root", ""); mysql_select_db("addressBook"); // Run a query $result = mysql_query("SELECT * FROM colleague"); ?> <!- HTML form opening tags --> <form action="action" method="post"> <select name="option"> <?php //for each row we get from mysql, echo a form input while ($row = mysql_fetch_array($result)) { echo "<option value=\"$row[value]\">$row[title]</option>\n"; } ?> <!- HTML form closing tags --> </select> <input type="submit"> </form> Link to comment https://forums.phpfreaks.com/topic/96033-dynamically-populating-a-drop-down-list-via-php/ Share on other sites More sharing options...
pocobueno1388 Posted March 13, 2008 Share Posted March 13, 2008 Try running this code and see what you get: <?php // Connect and select a database mysql_connect("localhost", "root", ""); mysql_select_db("addressBook"); // Run a query $result = mysql_query("SELECT * FROM colleague"); if (mysql_num_rows($result) > 0){ echo '<form action="action" method="post">' .'<select name="option">'; //for each row we get from mysql, echo a form input while ($row = mysql_fetch_array($result)) { echo "<option value='{$row['value']}'>{$row['title']}</option>\n"; } echo '</select>' .'<input type="submit">' .'</form>'; } else { echo "No results found" } ?> Also, make sure the rows "value" and "title" exist in the database. It sounds like it's returning the results, but there are no such rows. Link to comment https://forums.phpfreaks.com/topic/96033-dynamically-populating-a-drop-down-list-via-php/#findComment-491644 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.