Reputation: 4665
I am trying to update table and add data if it doesnt exist in the table row.
$data = "red flowers";
$id = "12";
mysql_query("update shares set data = data + '".$data."' WHERE id = '".$id."' LIMIT 1")
But it doesnt work. What is the correct way to do it ?
Upvotes: 1
Views: 43
Reputation: 967
Use the REPLACE
statement instead of UPDATE
.
It works exactly the same as a INSERT
statement, but it will replace the data if data with the same primary keys exists.
Ex:
mysqli_query("REPLACE INTO shares (id,data) values (".$id.",'".$data."')");
You should sanitize your data to avoid SQL Injection.
You need DELETE
privileges for this statement to work
Upvotes: 1
Reputation: 4329
First of all mysql_query is deprecated use mysqli_query or PDO.
Secondly don't use simple sql statements while constructing query. Use prepared statement , thereby preventing your code from mysql injections.
Thirdly, use http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html for insert if doesn't exist else update case.
Upvotes: 0