简体   繁体   English

为什么我的下拉列表没有填充表格数据?

[英]Why is my drop down list not populating with the table data?

WHy is my drop down list not populating with the table data? 为什么我的下拉列表没有填充表格数据? (dropdown box is empty) And what is used to display data upon selection of an item in that drop down - is it a "VIEW" (please do provide a study link so I can learn) (下拉框为空),然后在下拉菜单中选择一个项目时显示数据的方式-是“视图”(请提供学习链接,以便我学习)

My Code 我的密码

<?php
$con=mysqli_connect("localhost","root","","ismat_db");
//check connection
if(mysqli_errno($con))
{
echo "Can't Connect to mySQL:".mysqli_connect_error();
}
else
{
echo "Connected to mySQL</br>";
}

 //$query = 'SELECT FirstName FROM persons';
//$result = mysqli_query($con,$query);

$query = mysqli_query($con,"SELECT 'FirstName' FROM persons");

//print_r($query);

//echo '<select name="FirstName">';
echo "<select name= 'FirstName'>";
//while($row=mysqli_fetch_array($result))
while($row=mysqli_fetch_array($query))
{
echo $row;
//echo "<option value='".$row['FirstName']."'>".'</option>';
}
echo '</select>';

?>

Try this: 尝试这个:

echo "<option value='".$row['FirstName']."'>".$row['FirstName']."</option>";

Also seems that you are having an issue with the database query. 似乎您的数据库查询也有问题。 Swap your while loop with the following and see if it works 用以下内容交换您的while循环,看看是否可行

if ($result = $mysqli->query($query)) {

    while ($row = $result->fetch_assoc()) {
    echo "<option value='".$row['FirstName']."'>".$row['FirstName']."</option>";
    }

$result->free();
}

You had 2 errors: 您有2个错误:

I pointed the first in the comment: to print an option you must use this code: 我在注释中指出了第一个:要打印选项,您必须使用以下代码:

echo "<option value='". $row['FirstName']."'>".$row['FirstName']
 . '</option>';

The second is in your SQL: you are not selecting the FirstName field from the database, but a string 'FirstName' instead. 第二个是在您的SQL中:您不是从数据库中选择FirstName字段,而是一个字符串'FirstName'。 That's why it is printed twice as you said. 这就是为什么您要打印两次的原因。 Use this SQL to get the field: 使用以下SQL获取字段:

$query = mysqli_query($con,"SELECT FirstName FROM persons");

Also usually people put an id of the record and not a field, that may have possible duplicates into the value of an <option> . 通常,人们通常将记录的ID而不是字段的ID放在记录中,而字段ID可能与<option>的值重复。 So, I would have used: 因此,我将使用:

echo "<option value='". $row['id']."'>".$row['FirstName']
 . '</option>';

selecting the id from the database together with first name. 从数据库中选择ID和名字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM