2

I have found answers all over the place on how to INSERT or UPDATE if record already exists, a good approach is using the on duplicate key update or REPLACE, but I can't seem to find anywhere how to do this using a prepared statement. Is this possible?

EDIT:

Ok let me be more specific with my question:

If I have a mysqli prepared statement like this example:

if ($stmt = $mysqli->prepare("UPDATE test SET name= ?, age= ? WHERE iduser= ?")) {    
    $stmt->bind_param('ssi', $name, $age, $id);
    $stmt->execute();
}

In this case how can I build a on duplicate key update This is were Im stuck, I dont know how to use the "?" :

if ($stmt = $mysqli->prepare("INSERT INTO test (iduser, name, age) VALUES (?,?,?))){
ON DUPLICATE KEY UPDATE name=?,age=?")) {    
    $stmt->bind_param('iss', $id, $name, $age);
    $stmt->execute();
}
cincodenada
  • 2,877
  • 25
  • 35
azirion
  • 109
  • 1
  • 12
  • depends on your flavour of SQL. – Aron Oct 25 '13 at 01:35
  • And I would rather not use REPLACE if possible – azirion Oct 25 '13 at 02:06
  • http://dev.mysql.com/doc/refman/5.6/en/insert-on-duplicate.html – Aron Oct 25 '13 at 02:07
  • possible duplicate of [How do I update if exists, insert if not (aka upsert or merge) in MySQL?](http://stackoverflow.com/questions/1218905/how-do-i-update-if-exists-insert-if-not-aka-upsert-or-merge-in-mysql) – Aron Oct 25 '13 at 02:22
  • Aron, my question is regarding a Prepared Statement, you are pointing to the answers I have already seen :-/ – azirion Oct 25 '13 at 02:32
  • http://stackoverflow.com/questions/548541/insert-ignore-vs-insert-on-duplicate-key-update – Anthony Oct 25 '13 at 03:01
  • is this a JAVA question? Please tag accordingly. Parameterized queries are just SQL queries that you...parameterize. Just swap out the parameters in your query with your selected language's token. – Aron Oct 25 '13 at 04:01

1 Answers1

3

I may be missing something, but can you not just update the second bindParam to: $stmt->bind_param('issss', $id, $name, $age, $name, $age)?

If you don't know how the question marks work and are just copy/pasting code examples, I suggest you read up on mysqli or look into PDO.

cincodenada
  • 2,877
  • 25
  • 35