从MySQL数据库填充PHP下拉列表

时间:2010-10-08 09:21:20

标签: php mysql drop-down-menu

我正在尝试从只有一列(pathology_id)的mysql数据库表填充网页中的下拉列表。我知道那里有测试数据,但我能做的最好的是用字段名称填充框,而不是行值。我到目前为止的代码如下,任何人都可以建议如何获得更多的列名称?提前谢谢。

<?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) ?>

2 个答案:

答案 0 :(得分:1)

试试这个:

<?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);
?>

来自PHP: mysql_query()

mysql_list_fields只返回有关给定表的信息,而不是包含的数据。

答案 1 :(得分:0)

选择选项应该有关闭标记。

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>';