php - Dropdown list is empty
100
My dropdown list shows empty. I am not sure if my query returns any records. How can I find out if my query returned any result? Here is my code. Please let me know. I am stuck with this issue.
<?php $link = mysql_connect("localhost", "root", "root");
if (!$link) { die('Could not connect: ' . mysql_error()); }
echo 'Connected successfully';
mysql_select_db("mydb");
$sql = "SELECT state_id, state_code FROM states";
$result = mysql_query($sql) or die(mysql_error());
?>
<p>
<select name="vers">
<?
while($row = mysql_fetch_array($result)){
echo "<option value=\"".$row['state_id']."\">".$row["state_code"]."</option>";
}
?>
</select>
<?
mysql_close($link);
?>
Answer
Solution:
Test the success or failure of your query with
if (!$result)
and usemysql_num_rows()
to verify the number of rows returned. Rather thandie()
, you can display a better error to your user and possibly render different HTML, rather than just exit the script abruptly.UPDATE
Add an empty default option. Make sure its
value
attribute is not something you would retrieve from your database.Answer
Solution:
Try running the query directly against the database using a tool such as MySql Workbench
I suspect there are no results.
UPDATE: Given that 50 results are expected... can you try this version with minor updates and report back on any warnings or errors you can see.
Answer
Solution:
Run your query on your Database Server instead of through PHP and see if it returns any results. If you use shared hosting with MySQL, many hosts provide a phpmyadmin interface that lets you run SQL commands.
Answer
Solution:
you can use mysql_num_rows to find out how many elements you have in your
$result
Answer
Solution:
At first, you should check your table "states". If it is empty, your code is correct. For example, you can use PhpMyAdmin - http://www.phpmyadmin.net. Execute your query with phpMyAdmin