1

I have a database with following table test_users:

| id | Username | Password |
|  1 |    pat   |  *****   |
|  2 |   roger  |  *****   |
|  3 |  luke93  |  *****   |

And to insert a new row I use following code, and it works fine:

$sql = $conn->prepare("INSERT INTO `test_users` (`Username`, `Password`) VALUES (?,?)");
$sql->bind_param('ss',$name, $email);

But now i am trying to make a "update profile"-page and I wanted to use ON DUPLICATE KEY. That means I need to check if idexists and if so update the row. Neither Username or Password is Unique, but id is. I have a $_SESSION["id"] which is available if the user is logged in. Can I use that in some way? So how do I write a SQL-sentence that finds out if id exist, and if so, overwrite it with ON DUPLICATE KEY (or a better way)?

William82
  • 89
  • 7
  • Try if exists() function. Use the below link [Solution](http://stackoverflow.com/questions/12639407/sql-if-exists-update-else-insert-syntax-error) – Harsha W Apr 18 '17 at 04:47
  • Assign unique key of your unique field and try below query http://stackoverflow.com/questions/4205181/insert-into-a-mysql-table-or-update-if-exists – Suresh Suthar Apr 18 '17 at 04:49
  • check - https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html – Sougata Bose Apr 18 '17 at 04:51

4 Answers4

0

first write selct query and count num rows if its 0 then insert query fire else update query

0

UPDATE works the same as an insert. You just need to pass the WHERE condition. You can do this with the following code, Try it

$id = $_SESSION['id'];
$sql = "UPDATE test_users SET Username=?, Password=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param($Username, $Password, $id);
$stmt->execute();
Manjeet Barnala
  • 2,975
  • 1
  • 10
  • 20
0

Assign unique key of your unique field and try below query Insert into a MySQL table or update if exists

INSERT INTO test_user(id, username, password) VALUES(1, "test", "test") ON DUPLICATE KEY UPDATE    

username="test", password="test"
Community
  • 1
  • 1
Suresh Suthar
  • 794
  • 8
  • 15
0

Use INSERT ... ON DUPLICATE KEY UPDATE

QUERY:

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name="A", age=19

credits to Donnie

xcution
  • 91
  • 5
  • how does this work. It says value 1 in Id. Will it not update only where Id is 1? And if it is dynamic, what variable should I then use? – William82 Apr 18 '17 at 06:12