我正在尝试更新表格中的值:
+----+-------------+
| Id | Value |
+----+-------------+
| 1 | title |
+----+-------------+
| 2 | description |
+----+-------------+
| 3 | email |
+----+-------------+
| 4 | keywords |
+----+-------------+
如果PK已存在,我想更新值,否则插入新行。
submit.php:
include('../../include/config.php');
if($_POST['settings']){
$title=$_POST['title'];
$description=$_POST['description'];
$email=$_POST['email'];
$keywords=$_POST['keywords'];
$test=$db->query("UPDATE `settings` SET `value` = '$title' WHERE `id` =1, SET `value` = '$description' WHERE `id` =2,SET `value` = '$email' WHERE `id` =3, SET `value` = '$keywords' WHERE `id` =4;");
if($test){
echo "good";
}else{
echo "bad";
}
}
更新
对于现在阅读此问题的人,请勿使用此结构来存储您的网站设置。我不建议使用查询,因为它易受SQL注入
答案 0 :(得分:3)
考虑这个例子......
SELECT * FROM user;
+---------+------+
| user_id | name |
+---------+------+
| 1 | X |
| 2 | B |
| 3 | C |
+---------+------+
UPDATE user
SET name = CASE user_id WHEN 1 THEN 'A'
WHEN 2 THEN 'J'
WHEN 3 THEN 'K' END;
SELECT * FROM user;
+---------+------+
| user_id | name |
+---------+------+
| 1 | A |
| 2 | J |
| 3 | K |
+---------+------+
答案 1 :(得分:1)
只要您在Id字段中有唯一索引或主键,此查询实际上可以使用Mysql中的单个语句完成。
INSERT INTO `settings` (`id`,`value`) VALUES (1,?),(2,?),(3,?),(4,?)
ON DUPLICATE KEY UPDATE `value`=VALUES(`value`);
请参阅https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
上 INSERT ... ON DUPLICATE KEY 的文档