为什么我的else语句要运行两次代码


Why is my else statment running the code twice

我的代码:

  <?php
    $name = $_POST["name"];
//establishing connection through PDO
    require("database.php");
    try{
     //querying the firstname data from the people table    
        $sql = $conn->query("SELECT firstname FROM people");
    }catch (Exception $e) {
            echo "Data could not be retrieved from the database.";
            exit;
        }
//looping through the array of firstname and echoing it out if it equals to the user input of name. else just echo out sorry no match 
    while($theRow = $sql->fetch(PDO::FETCH_ASSOC)){
    if(strtolower( $name ) == strtolower( $theRow["firstname"] ) && isset($_POST['name']) ){
    echo $theRow['firstname'] . "<br />";
    }else {
        echo 'Sorry no match';
        exit;
    }
    }
    ?>

requiredatabase.php只是使用PDO建立与我的数据库的连接。

我的数据库中只有2行

的"名字"

  • Jack
  • Bob

如果有人在我的输入字段中键入这两个名称中的一个,php将从数据库中的people表中回显该名称。非常简单,但我遇到的唯一问题是在我的else语句上,我希望它能回显如果名称的输入字段不等于数据库中的任何名称,对不起没有匹配。但它的回声消失了对不起,每个名字都没有匹配一次。我知道我在数据库名称数组中循环,但我只想让它回显对不起,如果名称输入不等于数据库中的"名字",就没有匹配一次。

额外注意:

我还尝试使用foreach循环,而不是while循环和fetchAll方法,而不仅仅是fetch,但没有运气。基本上给了我同样的结果。

问题更新:

当我加载页面时,else语句已经生效,并且回显抱歉没有匹配甚至在我在输入中设置名称之前。如果我键入了错误的名称,它将回声对不起,没有匹配两次如果我键入正确的名称,它将从数据库中回显该名称和对不起没有匹配一次。

解决方案:

<?php
$name = $_POST["name"];
require("database.php");
try{
    $sql = $conn->prepare("SELECT firstname FROM people WHERE firstname = ?");
    $sql->bindParam(1,$name);
    $sql->execute();
}catch (Exception $e) {
        echo "Data could not be retrieved from the database.";
        exit;
    }
$theRow = $sql->fetch(PDO::FETCH_ASSOC);
if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
echo $theRow['firstname'] . "<br />";
}else{
    echo 'no match'; 
}
?>

事实证明,我甚至不需要对WHERE子句进行循环,只需要获得与$_POST['name']匹配的名字,所以问题只是什么时候输出这些数据,那就是if语句的时间。但如果我必须输出多个数据,我可能会使用foreach循环,如下所示:

if(strtolower( $name ) == strtolower( $theRow["firstname"] ) ){
foreach( $theRow as $row ){
    echo $row . "<br />";
    }
    }else{
        echo 'no match'; 
    }

如果有人看到这个代码或我的方法有任何问题,请告诉我。感谢

首先,您似乎回答了自己的问题:为什么else语句要运行两次代码?答案:不是;它为循环的每次迭代运行一次,因为你把它放在了循环中。

只需将SQL更改为:

$stmt = $conn->prepare("SELECT firstname FROM people where firstname = ?");
$stmt->execute(array($name));
$result = $stmt->fetchAll();

它将返回1行或0行。因此,您的if语句将如下所示:

if($result->num_rows) // True if num_rows > 0; else false

并将while循环放入您的if语句中。将其他语句保留为echo 'Sorry no match';