I'm trying to accomplish dynamic PDO prepared UPDATE statements using a customized array filled with $_POST data.
The array structure looks like this:
$data = array();
$data[00001] = array("description"=>"item1", "stock"=>"100");
$data[00002] = array("description"=>"item2", "thr_alert"=>"20");
The mysql columns have the same name as the array keys. The 'id' is the main array key (00001, 00002, etc).
My first approach was the method described here: php.net pdo execute()
foreach($data as $itemId=>$value) {
$keys = array_keys($value);
$fields = '`'.implode('`, `',$keys).'`';
$placeholder = substr(str_repeat('?,',count($keys)),0,-1);
echo "INSERT INTO `baz`($fields) VALUES($placeholder)";
print_r(array_values($value)); //values to fill up execute() later on
echo "<br>";
}
unset($keys, $fields, $placeholder, $itemId, $value);
Nice approach but doesn't work, as this is designed for INSERT prepared statements and can't be used for UPDATE as the syntax should be UPDATE foo SET bar = :bar/? WHERE id = :id/?.
Second approach:
$out = "UPDATE `baz` SET ";
foreach($data as $itemId=>$value) {
foreach($value as $column=>$foo) {
}
$out1 .= $column." = :$column, ";
$out2 = "WHERE id = :id";
}
$output = $out.rtrim($out1, ", ")." ".$out2."<br>";
echo $output;
Output:
UPDATE baz SET stock = :stock, description = :description WHERE id = :id
Notice that only the first array is displayed.
Any ideas on how to achive my goal ?
Move this line inside the second foreach loop
$out1 .= $column." = :$column, ";
But the result is awkward for the current data,since it will generate something like
...SET description = :description,description = :description....
Solved!
I had to unset($out1); after $output is written and execute the $out1 line in the second foreach loop (see code below).
$out = "UPDATE `foo` SET ";
foreach($data as $itemId=>$value) {
foreach($value as $column=>$foo) {
$out1 .= $column." = :$column, ";
}
$out2 = "WHERE id = :id";
$output .= $out.rtrim($out1, ", ")." ".$out2."<br>";
unset($out1);
}
echo $output;
The next step will be to prepare the statement using $db->prepare($output); and pass the data to $db->execute($data);.
So to answer my own question - yes, dynamic prepared statements using one "global" array IS possible ! :-)
来源:https://stackoverflow.com/questions/42175871/update-table-using-dynamic-prepared-statements