简体   繁体   English

如果mysql表中不存在user_id,如何插入新数据

[英]How to insert new data if user_id does not exist in mysql table

I have two columns into mysql table map 1. First column have name json , second have name user_id Now, I need to insert data to new row if user_id does not exist into mysql table, but if excist I need just to update json column where user_id = user_id ... 我在mysql表map有两列。第一列的名称为json ,第二列的名称为user_id现在,如果user_id在mysql表中不存在,我需要将数据插入新行,但是如果存在,我只需要更新json列即可用户ID =用户ID ...

I try: 我尝试:

     try {        
                $STH = $db->prepare("INSERT INTO map (user_id, json)
VALUES (:2,:1)
on duplicate key update json=values(json)");


                $STH->bindParam(':1', $_POST['mapData']);
                $STH->bindParam(':2', $user_id);

Some ideas? 一些想法? I use php pdo. 我使用php pdo。

How to solve this problem? 如何解决这个问题呢?

Thanks! 谢谢!

Just have a look at MySQLs REPLACE command. 看看MySQLs的REPLACE命令。 Cite from MySQL manual: 引用MySQL手册:

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted. REPLACE与INSERT的工作方式完全相同,只是如果表中的旧行与PRIMARY KEY或UNIQUE索引的新行具有相同的值,则在插入新行之前删除旧行。

That could be the solution to your problem. 那可以解决您的问题。 Otherwise, make a select, if the id exists, make an update, otherwise an insert. 否则,请进行选择(如果id存在),请进行更新,否则请进行插入。

You miss : in on duplicate key update json=values(:json)"); , so try like this: 您可能错过了:on duplicate key update json=values(:json)"); ,尝试这样:

     try {        
                $STH = $db->prepare("INSERT INTO map (user_id, json)
VALUES (:user_id,:json)
on duplicate key update json=values(:json)");
                $STH->bindParam(':json', $_POST['mapData']);
                $STH->bindParam(':user_id', $user_id);

Besides, your question is related to: Here 此外,您的问题与: 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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