PHP下拉列表没有选择值

时间:2018-01-05 12:27:27

标签: php html mysql html-select

我正在使用PHP从数据库中检索值,但我遇到了问题。当我从下拉列表中选择一个值并按下提交时,我输入的值未被选中。表单中的所有其他元素都可以完美地运行。我不确定我做错了什么。

使用isset时,最终结果不显示任何内容,而不是我在下拉菜单中选择的内容。

这是我的代码:

<?php 
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "timedrun";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
?>

<html>

<head>

<title>Add Run</title>

<link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'> 
<link rel='stylesheet' type='text/css' href='mystyle.css'>

</head>

<body>
<h1>Timed Run</h1>

<center>
<hr>

<form action='#' method='post'>
Select Student: <select name='studentSelected' class="form">

<?php
$fsql = "SELECT firstName FROM students";
$fresult = $conn->query($fsql);
$lsql = "SELECT lastName FROM students";
$lresult = $conn->query($lsql);


if ($fresult->num_rows > 0) {
    while ($row = $fresult->fetch_assoc()){
        echo '<option value="'.$row['ID'].'">' .$row['firstName'].' </option>';
    }
};

?>
</select>

<br><a class="space" ></a><br>

Time (s): <input type="int" name="time" class="form">

<br><a class="space"></a><br>

Select Date: <input type="date" name="date" class="form">

<br><a class="space"></a><br>

Notes: <input type="text" name="notes" class="form">

<br><a class="space"></a><br>

<input type="submit" class="form" name="submit">

</form>

<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['studentSelected'];
echo "You have selected :" .$selected_val;
}
?>
</center>
</body>
</html>

3 个答案:

答案 0 :(得分:3)

这是因为您没有在查询中选择ID。将您的查询更改为:

$fsql = "SELECT ID,firstName FROM students"; // add ID
$fresult = $conn->query($fsql);
$lsql = "SELECT ID,lastName FROM students";// add ID
$lresult = $conn->query($lsql);

答案 1 :(得分:3)

<?php
$fsql = "SELECT firstName FROM students";
$fresult = $conn->query($fsql);
$lsql = "SELECT lastName FROM students";
$lresult = $conn->query($lsql);


if ($fresult->num_rows > 0) {
    while ($row = $fresult->fetch_assoc()){
        echo '<option value="'.$row['ID'].'">' .$row['firstName'].' </option>';
    }
};

您的查询仅用于表中的select firstname并使用value="'.$row['ID'].'"。将您的查询更改为

SELECT ID,firstName FROM students

答案 2 :(得分:1)

现在它应该工作

<?php
// $fsql = "SELECT * FROM students";
$fsql = "SELECT ID,firstname FROM students";
$fresult = $conn->query($fsql);

if ($fresult->num_rows > 0) {
    while ($row = $fresult->fetch_assoc()){
        echo '<option value="'.$row['ID'].'">' .$row['firstName'].' </option>';
    }
};