【问题标题】:Undefined variable BEFORE SUBMIT is clicked [duplicate]单击提交之前未定义的变量[重复]
【发布时间】:2019-09-11 04:29:44
【问题描述】:

一开始不使用提交按钮时,出现未定义变量错误

注意:未定义变量:导致第 31 行的 C:\xampp\htdocs\01test\index.php

警告:mysqli_fetch_array() 期望参数 1 为 mysqli_result,在第 31 行的 C:\xampp\htdocs\01test\index.php 中给出 null

代码在使用提交时有效。

这是我的代码 [a link](https://pastebin.com/geBjQDGC/)!

使用提交按钮后一切正常。 但是在第一次使用之前,有两个错误。

【问题讨论】:

  • 这里是邮政编码。

标签: php mysql post filter


【解决方案1】:

注意:未定义的变量:导致 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))

所以你的$resultsif-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

【讨论】:

  • @ShafinAqrin 很高兴知道它有帮助。如果它有帮助,你可以接受这个作为答案并投票。
  • 我的声望低于 15,所以我无法投票 >.
  • @ShafinAqrin :) 没关系。快乐编码...
猜你喜欢
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 2013-11-16
相关资源
最近更新 更多