我想从一个表中的一列中检索每一行,并将它们全部放在一个元素中。 我现在几乎在黑暗中挣扎,我做错了什么/失踪了?
$db_connect = mysql_connect("$host", "$db_username", "$db_password");
$db_select = mysql_select_db("$db_name");
mysql_set_charset('utf8', $db_connect);
$db_query_project="SELECT * FROM $tbl_name";
print('<form name="report" method="post" action="">');
print('<label for="project">Projekt </label>');
print('<select name="project_select">');
print('<option>Test</option>');
foreach ($db_query_project as $key => $value){
print('<option>'.$key['project_name'].'</option>');
}
print('</select>');
print('</form>');
还有更好的方法吗?
答案 0 :(得分:1)
您需要连接到数据库并执行查询才能检索数据并获取数据。为此,您可以使用mysqli或PDO。以下是如何使用mysqli从列$tbl_name
中获取数据project_name
的示例。
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ")";
exit();
}
$query = "SELECT * FROM `$tbl_name`";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s \n", $row["project_name"]);
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
答案 1 :(得分:0)
我更喜欢这个:
function getFieldSelect($name, $selected, $values, $attributes) {
$r = "<select name=\"$name\" $attributes>";
foreach ($values as $k => $v) {
if ($k == $selected) {
$sel = "selected";
} else {
$sel = "";
}
$r .= "<option value=\"$k\" $sel>$v</option>\n";
}
$r .= "</select>";
return $r;
}
我从DB获取了值并以数组格式将其提供给我的函数。我认为这是打印选择字段最灵活的方式。您可以使用数据库来获取值或任何数组。
答案 2 :(得分:-1)
<?php
$db_query_project= mysql_query("SELECT * FROM $tbl_name");
echo '<form name="report" method="post" action="">';
echo '<label for="project">Projekt </label>';
echo '<select name="project_select">';
echo '<option>Test</option>';
while( $row = mysql_fetch_assoc( $db_query_project ) )
{
echo '<option>'.$row['project_name'].'</option>';
}
echo '</select>';
echo '</form>';