简体   繁体   中英

Slim Framework - Multiple PDO updates from json

Im trying to do multiple inserts in a json put request using the Slim framework and I get a strange error of:

SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: 'Chester'

Even though the Name is a VARCHAR. It errors on the $sth->execute line. If I only use one entry it sometimes works. Here is the JSON

[{"id":"2240","name":"Cheats","breed": "Maltys"},
{"id":"2241","name":"Chester","breed":"Poodlexx"}]

Code:

$app->put('/test2', function ($request, $response, $args) {
    $parsedBody = $request->getParsedBody();
    print_r ($parsedBody);
    foreach ($parsedBody as $key => &$value) {
        if (!isset($value['id'])) { continue; }
        $sql = "UPDATE pets p SET";
        foreach ($value as $p_key => &$p_value) {
            if ($p_key !== 'id') { //ignore the id
                $sql .= " $p_key = :$p_key AND";
            }
        }
        $sql = preg_replace('/AND$/', '', $sql)." WHERE p.id = :id";
        //echo "\n$sql";
        $sth = $this->db->prepare($sql);
        foreach ($value as $p_key => &$p_value) {
            //echo "\n$p_key:$p_value";
            $sth->bindParam($p_key, $p_value);
        }
        $sth->debugDumpParams();
        $sth->execute();
    }
    return;
});

Output of DumpParams:

SQL: [67] UPDATE pets p SET name = :name AND breed = :breed  WHERE p.id = :id

Doh, after 2 hours of banging my head it was an incorrect SQL statement should have been a comma not an AND:

 foreach ($value as $p_key => &$p_value) {
            if ($p_key !== 'id') { //ignore the id
                $sql .= " $p_key = :$p_key,";
            }
        }
        $sql = preg_replace('/,$/', '', $sql)." WHERE p.id = :id";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM