$_POST['data'] contains an id and other fields that need to be inserted in a DB row with this id.
Is there a way to avoid redundancy in this code:
$data = json_decode($_POST['data'], true);
$db = new PDO('sqlite:data.db');
$stmt = $db->prepare("UPDATE test SET a=?, b=?, c=?, d=?, e=?, f=? WHERE id=?");
$stmt->execute(array($data['a'], $data['b'], $data['c'], $data['d'], $data['e'], $data['f'], $data['id']));
How to avoid to repeat the column names a, ..., f twice, once in the prepared statement, and once in the array?
Can we totally avoid to hardcode the column names a, ..., f, and just infer them from the $data array keys?
CodePudding user response:
You can make it a little easier by using named placeholders rather than ?. Then you can just pass $data as the argument to execute()
$stmt = $db->prepare("UPDATE test SET a=:a, b=:b, c=B, d=:d, e=:e, f=:f WHERE id=:id");
$stmt->execute($data);
This just moves the redundancy from the execute() parameter to the placeholders. But it's less verbose.
