daninthemix
daninthemix

Reputation: 2570

MySQL updating an unknown number of fields

With an INSERT statement I can do something like this, passing in an unknown number of placeholders and values:

$insert_SQL = $db->prepare("INSERT INTO laptops ($fields) VALUES ($placeholders)");
$insert_SQL->execute([$values]);

Is there a similar method when you're updating a record but don't know the number of values? Something like this:

$update_SQL = $db->prepare("UPDATE laptops ($fields) VALUES ($placeholders) WHERE id = $id");
$update_SQL->execute([$values]);

Upvotes: 1

Views: 219

Answers (1)

Matt S
Matt S

Reputation: 15374

Sort of. You could use REPLACE INTO:

$update_SQL = $db->prepare("REPLACE INTO laptops ($fields) ($placeholders)");
$update_SQL->execute([$values]);

Caveats:

  • $fields must include id. $values must include $id.
  • The table must have a primary key or unique index on id. It uses this to determine if a matching row already exists.
  • It will delete and insert a row, not actually update it. This might matter if you have triggers on the table or for some performance considerations.

Upvotes: 1

Related Questions