简体   繁体   中英

Insert into database and check if row already exist

I have simple input and I need help with MySQL.

When you click the submit button, PHP will need to check if the row already exist and only insert a new one if not.

I know the INSERT part, but don't know how to check if the row already exists.

Either use INSERT IGNORE to do nothing if it already exists, or ON DUPLICATE KEY UPDATE to update fields on attempted insert.

EDIT

If you want to check to see if it exists, run a SELECT first, either as SELECT * FROM TABLE WHERE ... and count the rows, or SELECT COUNT(*) FROM TABLE WHERE ... and check if the count is greater than 0 . If it exists, send a message to the user. If it does not, then go ahead and insert.

$result = mysqli_query($con,"SELECT email FROM user WHERE email='".$email."'");
$count=mysqli_num_rows($result);
if($count==0)  {
$sql="INSERT INTO user (email)VALUES('".$email."')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header('Location:login.php');
}
else
{ 
echo 'already exist';
}

try this one

无需检查条目是否已经存在,也无需检查phpmyadmin和该特定表,该表对于该条目和那是唯一的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM