为什么我的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;
    }
    }
    ?>

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

我的数据库中只有 2 行

'firstname' of

  • 杰克
  • 鲍勃

如果在我的输入字段中有人键入这两个名字之一 php 将从数据库中的人 table 中回显该名字。非常简单,但我遇到的唯一问题是在我的 else 语句中,如果名称的输入字段不等于数据库中的任何名称,我希望它回显 Sorry no match。但相反,它回显了抱歉,每个名字都没有匹配一次。我知道我正在遍历数据库名称数组,但我只希望它在数据库中输入的名称不等于 "firstname" 时回显 Sorry no match 一次.

额外说明:

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

问题更新:

When I load the page the else statement is already taking effect and echoing out Sorry no match even before I set a name in the input. and if I type the wrong name it ill echo out Sorry no match twice if I type the correct name it will echo out the name out of the database and Sorry no match once.

想出来了:

<?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();

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

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

并将您的 while 循环 放入 您的 if 语句中。将您的 else 语句保持为 echo 'Sorry no match';.