update table using dynamic prepared statements

好久不见. 提交于 2019-12-05 06:34:51

问题


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 ?


回答1:


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....



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!