要回答你的問題,直接,你應該首先檢查是否有任何錯誤(mysql_error()
),然後檢查是否有一些結果(mysql_num_rows
) - 這些使得代碼更容易調試,因爲它會告訴你什麼是錯誤的。
試試這個;
<?php
// Connect with user
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("disertation", $con);
// Run query
$results = mysql_query("SELECT `name` FROM `user_parent`;") or die (mysql_error());
// Check for no results
if (mysql_num_rows($results) == 0)
{
echo 'There are no options for you to select.';
}
else
{
// If results, loop them.
// If the names are user input, make sure they're displayed in non-raw form
echo '<select name="name">
<option value="name">Select one</option>';
while($row = mysql_fetch_assoc($results))
{
$name = htmlentities($row['name'], ENT_QUOTES, "UTF-8");
echo '<option value=" ' . $name . ' ">' . $name . '</option>';
}
echo '</select>';
}
將與mysqli_解決方案編輯,如果這是你的一個選擇,因爲mysql_已被棄用,並將從PHP的支持下降,遲早的事。
MySQLi解決方案;
<?php
// Connect to database;
$mysqli = new mysqli("localhost", "my_user", "my_password", "data_base");
if (mysqli_connect_errno())
{
die("Connect failed: " . mysqli_connect_error());
}
$result = $mysqli->query("SELECT `name` FROM `user_parent`");
if ($result->num_rows > 0)
{
echo '<select name="name">
<option value="name">Select one</option>';
while($row = $result->fetch_assoc)
{
$name = htmlentities($row['name'], ENT_QUOTES, "UTF-8");
echo '<option value=" ' . $name . ' ">' . $name . '</option>';
}
echo '</select>';
$result->close();
}
else
{
echo 'There are no options for you to select.';
}
你有沒有在db中運行查詢,是返回結果? –
'mysql_select_db(「disertation」,$ con); $ results = mysql_query(「SELECT name FROM user_parent;」);' – BE57
使用mysqli而不是mysql推薦 –