我尝试做的是我的数据库中的INSERT
个订阅者,但是IF EXISTS
它应该UPDATE
行,ELSE INSERT INTO
一个新行。
当然,我首先连接到数据库,然后从网址字符串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);
但它们都不起作用,我做错了什么?
非常感谢任何帮助!
答案 0 :(得分:181)
在subs_email
列上创建UNIQUE
constraint,如果尚不存在:
ALTER TABLE subs ADD UNIQUE (subs_email)
使用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 ... ON的INSERT部分的列值 DUPLICATE KEY UPDATE - dev.mysql.com
答案 1 :(得分:-2)
尝试一下:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';