[英]Populate a PHP Dropdown List from MySQL Database
I'm trying to populate a dropdown list in my web page from a mysql database table which has only one column (pathology_id). 我正在尝试从只有一个列(pathology_id)的mysql数据库表中填充网页中的下拉列表。 I know there is test data in there but the best I can do is populate the box with the field name, not the row values.
我知道那里有测试数据,但是我能做的最好的就是用字段名称而不是行值填充框。 The code I have thus far is below, can anyone suggest how to get more than just the column name?
到目前为止,我的代码在下面,有人可以建议如何获得不仅仅是列名的方法吗? Thanks in advance.
提前致谢。
<?php $con = mysql_connect("localhost","dname","dbpass");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
$fields = mysql_list_fields("dbname","PATHOLOGY",$con);
$columns = mysql_num_fields($fields);
echo "<form action = newcase.php method = POST><select name = Field>";
for($i = 0; $i < $columns ; $i++)
{
echo "<option value = $i>";
echo mysql_field_name($columns , $i);
}
echo "</select></form>";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added";
}
mysql_close($con) ?>
Try this: 尝试这个:
<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
From PHP: mysql_query() . 从PHP:mysql_query() 。
mysql_list_fields
just returns information about a given table, NOT the data contained. mysql_list_fields
只是返回有关给定表的信息,而不是包含的数据。
Select option should has close tag. 选择选项应带有关闭标签。
echo '<form action="newcase.php" method="POST"><select name"="Field">';
for($i = 0; $i < $columns ; $i++)
{
echo '<option value="' . $i . '">';
echo mysql_field_name($columns , $i);
echo '</option>';
}
echo '</select></form>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.