我想要做的就是INSERT在我的数据库的用户,但IF EXISTS它应该UPDATE排,ELSE INSERT INTO一个新行。
INSERT
IF EXISTS
UPDATE
ELSE INSERT INTO
Ofcourse我连接到数据库第一和GET的$name,$email并$birthday从URL字符串。
GET
$name
$email
$birthday
$con=mysqli_connect("localhost","---","---","---"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $name=$_GET['name']; $email=$_GET['email']; $birthday=$_GET['birthday'];
可以,但是只添加新行;
mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday')"); mysqli_close($con);
这是我尝试过的;
mysqli_query($con,"INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES '$name', '$email', '$birthday' ON DUPLICATE KEY UPDATE subs_name = VALUES($name), subs_birthday = VALUES($birthday)"); mysqli_close($con);
和
mysqli_query($con,"IF EXISTS (SELECT * FROM subs WHERE subs_email='$email') UPDATE subs SET subs_name='$name', subs_birthday='$birthday' WHERE subs_email='$email' ELSE INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday')"); mysqli_close($con);
mysqli_query($con,"IF NOT EXISTS(SELECT * FROM subs WHERE subs_email='$email') Begin INSERT INTO subs (subs_name, subs_email, subs_birthday) VALUES ('$name', '$email', '$birthday') End"); mysqli_close($con);
但是它们都不起作用,我在做什么错?
任何帮助是极大的赞赏!
如果不存在UNIQUE约束,请在您的subs_email列上创建约束:
UNIQUE
subs_email
ALTER TABLE subs ADD UNIQUE (subs_email)
用途INSERT ... ON DUPLICATE KEY UPDATE:
INSERT ... ON DUPLICATE KEY UPDATE
INSERT INTO subs
(subs_name, subs_email, subs_birthday) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE subs_name = VALUES(subs_name), subs_birthday = VALUES(subs_birthday)
您可以在UPDATE子句中使用VALUES(col_name)函数来引用INSERT的INSERT部分中的列值。… ON DUPLICATE KEY UPDATE-dev.mysql.com