問題描述
$query = $pdo -> prepare("SELECT * FROM Users WHERE Username =:Username");
$query->bindParam(':Username', $name);
$query->execute();
$nameRes = $query->fetch(PDO::FETCH_ASSOC);
if ($nameRes['Username']==$_POST['username']) {
die ("Username is already in use!");
}
$query = $pdo -> prepare("SELECT * FROM Users WHERE Email =:Email");
$query->bindParam(':Email', $email);
$query ->execute();
$emailRes = $query->fetch(PDO::FETCH_ASSOC);
if ($emailRes['Email']==$_POST['email']) {
die ("Email is already in use!");
}
我在我的應用程序的注冊頁面上有這個代碼,當用戶名可以免費使用但電子郵件不是,反之亦然我得到這個
I have this code on the registration page of my app and when Username is free to use but email is not and vice versa I get this
注意:嘗試訪問 bool 類型值的數組偏移量
Notice: Trying to access array offset on value of type bool
好的,結果返回false,但在這種情況下該怎么辦?注意:這是在 php v7.4 上,同樣的事情在 v7.3 上工作
Ok the result is returning false but what to do in this situation? Note: This is on php v7.4 this same thing was working on v7.3
推薦答案
您收到此錯誤可能是因為在數據庫中找不到符合您條件的記錄.
解決此錯誤的最簡單方法是先檢查數據庫是否返回任何內容.
The easiest way to solve this error is to check if the database returned anything first.
$emailRes = $query->fetch(PDO::FETCH_ASSOC);
// VVV - Here I am checking if there was anything returned and then I check the condition
if($emailRes && $emailRes['Email']==$_POST['email']) {
// ...
}
如果您不在乎數據庫是否返回任何內容,那么您可以簡單地提供一個默認值.例如:
If you don't care whether the database returned anything, then you can simply provide a default value. For example:
$emailRes = $query->fetch(PDO::FETCH_ASSOC);
$email = $emailRes['Email'] ?? ''; // default: empty string
使用 PDO 檢查 DB 中是否存在的正確方法是:
The correct way to check for existance in DB using PDO is:
$query = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Username =:Username");
$query->execute([':Username' => $name]);
if ($query->fetchColumn()) {
throw new Exception("Username is already in use!");
}
$query = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Email =:Email");
$query->execute([':Email' => $email]);
if ($query->fetchColumn()) {
throw new Exception("Email is already in use!");
}
我沒有在 PHP 中獲取行并再次進行比較,而是從數據庫中獲取匹配行的計數,并將該計數用作 if
語句中的布爾值.fetchColumn()
將從第一行獲取單列,如果我使用 COUNT(*)
我知道總會有一行.
Instead of fetching the row and doing the comparison again in PHP I am fetching a count of matching rows from the database and I use that count as a boolean in the if
statement. fetchColumn()
will fetch a single column from the first row and if I use COUNT(*)
I know there will always be one row.
您也可以在一個查詢中完成:
You can also do it in one query:
$query = $pdo->prepare("SELECT COUNT(*) FROM Users WHERE Username =:Username OR Email =:Email");
$query->execute([':Username' => $name, ':Email' => $email]);
if ($query->fetchColumn()) {
throw new Exception("Username or email is already in use!");
}
這篇關于嘗試訪問 bool 類型值的數組偏移量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!