[英]Insert multiple Data to MySQL and Update if existing
我在同时插入和更新数据库时遇到问题,我有一个表单,用户可以编辑信息或添加新字段,我想要的是用户编辑表单时以及如果用户添加了新文件,我希望我可以一起插入和更新数据库。
这是我的代码
function insert_update_db(){
global $db;
$section = $_POST["page"];
$fieldsArray = array( "section_id", // Primary key
"section_title",
"section_name",
"section_content",
);
$fields = '`' . implode('`, `', $fieldsArray ) . '`';
$sql = "INSERT INTO `db_section` ($fields) VALUES";
$valueArray = array();
$indexKey = array();
foreach ($section["section"] as $value) {
$section_id = ($value["section_id"] != "" ? $db->quote($value["section_id"]) : "NULL" ); // Check if curr field has a ID
$title = $value["title"];
$name = $value["name"];
$content = $value["content"];
$valueArray[] = "($section_id, '$title','$name', '$content')";
if($section_id != "NULL"){
$indexKey[] = str_replace("'", "", $section_id);
$sql_update = "UPDATE `db_section` SET
`section_title` = '$section_title',
`section_name` = '$name',
`section_content` = $content
WHERE `section_id` = $section_id;";
$update = $db->query($sql_update);
echo $sql_update;
if($update){
$db->sql_status = "Success";
}
}
}
$sql .= implode(",", $valueArray);
$sql .= " ON DUPLICATE KEY UPDATE ";
$sql .= "section_id=" . implode(" AND section_id=", $indexKey);
$insert = $db->query($sql);
if($insert){
$db->sql_status = "Success";
}else{
$db->sql_status = "Error";
}
}
在编辑页面中,我添加了隐藏的输入section_id
以获取正在编辑的字段的主键,并且将为新字段提供NULL
,如果section_id != 'NULL'
则尝试执行操作,然后UPDATE
该字段。
我尝试使用ON DUPLICATE KEY UPDATE
来检查section_id
是否重复,但它根本不起作用。
对不起,我的英语,我们将不胜感激:)
它所要做的只是一个索引冲突,该冲突将违反要更新的行而不是要创建的新行的重复项。 索引冲突可以是一个主键,一个在另一个索引上可以是主键,可以是单列,也可以是跨多列的复合索引。
当然,以下内容相当la脚,但正如我现在所能想象的那样。
create table user
(
id int auto_increment primary key,
userName varchar(20) not null,
friendCount int not null,
unique key(userName)
);
insert user(userName,friendCount) values('Jason7',0) on duplicate key update friendCount=friendCount+1;
select * from user;
+----+----------+-------------+
| id | userName | friendCount |
+----+----------+-------------+
| 1 | Jason7 | 0 |
+----+----------+-------------+
insert user(userName,friendCount) values('Fred',0) on duplicate key update friendCount=friendCount+1;
select * from user;
+----+----------+-------------+
| id | userName | friendCount |
+----+----------+-------------+
| 1 | Jason7 | 0 |
| 2 | Fred | 0 |
+----+----------+-------------+
insert user(userName,friendCount) values('Fred',0) on duplicate key update friendCount=friendCount+1;
+----+----------+-------------+
| id | userName | friendCount |
+----+----------+-------------+
| 1 | Jason7 | 0 |
| 2 | Fred | 1 |
+----+----------+-------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.