問題描述
我有以下代碼:
$check = $dbh->prepare("SELECT * FROM BetaTesterList WHERE EMAIL = ?");
$check->execute(array($email));
$res = $check->fetchAll();
if (!($res['EMAIL'])){
$stmt = $dbh->prepare("INSERT INTO BetaTesterList(EMAIL) VALUES (?)");
$stmt->execute(array($email));
} else {
$return['message'] = 'exists';
}
然而,盡管該記錄已存在于數據庫中,但這仍會插入該值.我如何防止這種情況?
However this still inserts the value although the record already exists in the DB. How do I prevent this?
推薦答案
這里有幾件事...
PDOStatement::fetchAll()
返回一個數組數組.要檢查記錄,請嘗試
PDOStatement::fetchAll()
returns an array of arrays. To check for a record, try
if (count($res) == 0) {
// no records found
}
開啟 E_NOTICE
錯誤.您應該知道 $res['EMAIL']
是一個未定義的索引.在腳本的頂部...
Turn on E_NOTICE
errors. You would have known that $res['EMAIL']
was an undefined index. At the top of your script...
ini_set('display_errors', 'On');
error_reporting(E_ALL);
我建議為您的 EMAIL
列創建唯一約束.這樣,您將無法插入重復的記錄.如果嘗試,PDO 將觸發錯誤或拋出異常,具體取決于您如何配置 PDO::ATTR_ERRMODE
屬性(請參閱 http://php.net/manual/en/pdo.setattribute.php)
I'd recommend creating a unique constraint on your EMAIL
column. That way, you would not be able to insert a duplicate record. If one was attempted, PDO would trigger an error or throw an exception, depending on how you configure the PDO::ATTR_ERRMODE
attribute (see http://php.net/manual/en/pdo.setattribute.php)
如果您不想這樣做,請考慮改用此查詢...
If you're not inclined to do so, consider using this query instead...
$check = $dbh->prepare("SELECT COUNT(1) FROM BetaTesterList WHERE EMAIL = ?");
$check->execute(array($email));
$count = $check->fetchColumn();
if ($count == 0) {
// no records found
} else {
// record exists
}
這篇關于檢查 PDO Fetch select 語句何時返回 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!