注意:未定义的变量:导致
C:\xampp\htdocs\01test\index.php 在第 31 行
根据上面的错误,第31行的语句是,
while($row = mysqli_fetch_array($results))
所以根据错误,问题出在下面的语句中。
$results = mysqli_query($dblink, $query) or die (mysqli_error());
以上语句在您的if-else 语句中。由于您已在 if 语句中声明并分配了该变量,因此您将收到该错误,因为无法从外部访问它。所以我建议你在if 语句之外声明变量$results。但是等一下,你还有另一个错误。
警告:mysqli_fetch_array() 期望参数 1 为 mysqli_result,
第 31 行 C:\xampp\htdocs\01test\index.php 中给出的 null
$results = mysqli_query($dblink, $query) or die (mysqli_error());
从下面的语句你正在解析上面的变量,
while($row = mysqli_fetch_array($results))
所以你的$results 在if-else 语句中。但是您已经从mysqli_fetch_array() 中的if 语句之外调用它。您的 if 条件是检查您是否提交了帖子。由于您没有提交和您的以下代码
while($row = mysqli_fetch_array($results))
在if条件之外$results给你null值。简而言之,无论您是否提交了帖子,您的代码 while($row = mysqli_fetch_array($results)) 都会调用 $results。所以现在你可以理解问题所在了。
所以最后,你的代码应该是这样的,
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "abc";
$dblink = mysqli_connect($servername,$username,$password,$database);
if(isset($_POST['submit'])) {
if($_POST['select']=='all_records') {
$query = "SELECT Kod_Dorm FROM dorm";
} elseif($_POST['select']=='A302') {
$query = "SELECT Kod_Dorm FROM dorm WHERE Kod_Dorm = 'A302'";
} elseif($_POST['select']=='A303') {
$query = "SELECT Kod_Dorm FROM dorm WHERE Kod_Dorm = 'A303'";
}
$results = mysqli_query($dblink, $query) or die (mysqli_error());
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($results)) { //Creates a loop to loop through results
echo "<tr><td>".$row['Kod_Dorm']."</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML
}
?>
通过将以下代码放入 if 语句将解决您的问题,因为如果您只提交表单,那么它将获取值。希望对您有所帮助!
echo "<table>"; // start a table tag in the HTML
while($row = mysqli_fetch_array($results)) { //Creates a loop to loop through results
echo "<tr><td>".$row['Kod_Dorm']."</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>"; //Close the table in HTML