簡體   English   中英

為什么$ stmt-> execute總是返回true?

[英]Why does $stmt->execute always return true?

即使無法識別輸入的id$stmt->execute仍返回true,因此程序永遠不會輸出“ ID或密碼錯誤!”。 我究竟做錯了什么?

$id = $_POST["id"];
$pwd = $_POST["pwd"];

include("./sql/connect.php");

$stmt = $db->prepare("SELECT * FROM list WHERE id = :id AND pwd = :pwd");

$stmt->bindValue(":id", $id);
$stmt->bindValue(":pwd", $pwd);

if($stmt->execute()){
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo $row["name"];
    }
}else{
    echo "Wrong ID or Password!";
}

您的查詢不會失敗,它返回0個結果,因此$stmt->execute()在這種情況下將返回true。 一個簡單的解決方法是將結果傳遞給數組,然后檢查結果是否為空。 檢查出Example #2 Counting rows returned by a SELECT statementPDOStatement對象::行數它解釋了為什么你不應該使用rowCount時一個SELECT和一個簡單的方法做同樣的事情,但通過使用第二查詢第一計數返回行。 我個人不會使用第二個查詢,因此這是編輯后的示例。

if($stmt->execute()) {
    $out = [];
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $out[] = $row["name"];
    }
    if(empty($out)) {
       echo "no matching user is found";
    } else {
       // rest of your code
    }
} else {
    return $db->errorInfo();
}

PS:我要感謝那些反對者。 謝謝,答案確實需要編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM