This question already has an answer here:
- mysql insert error 1062 5 answers
In my mysql database I set the 'email' field as a unique constraint. I don't want two or more users to have the same email address. I created this function to check that. I only want the function to run if a different user tries to use the same address. This is the function:
<?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...");
}
}
}
?>
This function is called up in a script that allows an admin to check users name, email, and last name. The username can't be changed. This is the script that I've updated. This is the script:
<?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");
?>
This is the error: That email is already in use (from the function). It does check if the email is in use, but it throws another error:
Ouch, failed to run query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicata du champ 'marx@fun.org' pour la clef 'email'
(this error is from the script).
I called up the function in the middle of the script. My issue is were should I use the function, and have it only run when a user tries to use the same address. Thank you in advance.
</div>