如何检查数据库中是否已存在电子邮件,如果存在,则更新它

时间:2017-09-05 19:35:16

标签: php mysql mysqli

//queries that have to be run.
$sql1="INSERT INTO user (userEmail,fname,lname,mobileno,designation,institution,userPassword,loginToken,userType,status,created,modified)
VALUES ('$userEmail','$fname','$lname','$mobileno','$designation','$institution','$hash',UUID(),'$userType','active',CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP())";

$sql2="INSERT INTO authorDetail (id,paperName,paperId,paymentStatus)
VALUES ('$last_id', '$paperName', '$paperId', '$paymentStatus')";

$sql3="SELECT id FROM user WHERE userEmail = '$userEmail'";


echo "check 3"."<br>";
//connection to update the inserted data from an html form
if (mysqli_query($connect, $sql1))



                    {
                            $last_id = mysqli_insert_id($connect);
                            echo "New record created successfully. Last inserted ID is: " . $last_id; // code for getting the last entered data in the table
                    }
                    else
                    {
                        $lastlast_id = mysqli_insert_id($connect);
                            echo "Error: " . $sql1 . "<br>" . mysqli_error($connect); //this checks for the validation of email from the user table
                            echo "checkcheck";

                    }

echo "check 4"."<br>";

// code for updating the foreign key mapped table

if (mysqli_query($connect, $sql2)) 
{
        $last_id = mysqli_insert_id($connect);
        echo "New record created successfully. Last inserted ID is: " . $last_id; //finding the id of the last inserted data+
} else {

    enter code here

        echo "Error: " . $sql2 . "<br>" . mysqli_error($connect);
}
echo "check5"."<br>";
                    mysqli_close($connect);
echo "check 6"."<br>";

1 个答案:

答案 0 :(得分:0)

您可以通过查询轻松完成,

INSERT INTO t1 (a,b,c) VALUES (1,2,3)

ON DUPLICATE KEY UPDATE c=c+1;

源: https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

相关问题