在我的mysql數據庫中,我將'email'字段設置爲唯一約束。我不希望兩個或更多用戶擁有相同的電子郵件地址。我創建了這個函數來檢查。如果不同的用戶試圖使用相同的地址,我只希望該函數能夠運行。這是函數:引發QLSTATE的唯一約束[23000]:完整性約束違規:1062因爲唯一約束而重複
<?php
function Email_gogo() {
if(!empty($_POST['email']))
{
$mysql_hostname = '*****';
$mysql_username = '*****';
$mysql_password = '*****';
$mysql_dbname = '*****';
try {
$db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", `enter code here`$mysql_username, $mysql_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit($e->getMessage());
}
$query_email = "
SELECT
email
from users
where
email = :email
";
$query_goes = array(
':email' => $_POST['email']
);
Try{
$stmt = $db->prepare($query_email);
$stmt ->execute($query_goes);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
}
}
catch(PDOException $ex){
echo 'ERROR: '. $ex->getMessage();
}
if($stmt->rowCount() > 0){
echo("That Email is already in use...");
}
}
}
?>
此功能在腳本,讓管理員檢查用戶的姓名,電子郵件和姓叫了起來。用戶名不能更改。這是我更新的腳本。這是腳本:
<?php
require("common.php");
require_once("gogo.php");
if(empty($_SESSION['user']))
{
header("Location: ../hound/login.php");
die("Redirecting to ../hound/login.php");
}
if(!empty($_POST))
{
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Please enter a valid email address...");
}
}
Email_gogo();
$array_value = array(
':email' => $_POST['email'],
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':id' => $_POST['id']
);
$query = "UPDATE users
SET
email = :email,
first_name = :first_name,
last_name = :last_name
WHERE
id = :id
";
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($array_value);
}
catch(PDOException $ex)
{
die("Ouch, failed to run query: " . $ex->getMessage());
}
header("Location: users.php");
die("Redirecting to users.php");
?>
這是錯誤:該電子郵件已在使用中(從函數)。它確實檢查電子郵件是否正在使用,但它會引發另一個錯誤:
Ouch, failed to run query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicata du champ '[email protected]' pour la clef 'email'
(此錯誤來自腳本)。
我在腳本中間調用了函數。我的問題是我應該使用該函數,並讓它只在用戶嘗試使用相同地址時運行。先謝謝你。
看看http://stackoverflow.com/questions/18643648/mysql-insert-query-returns-error-1062-23000-duplicate-entry-2147483647-for – daremachine