PHP generate dynamic PDO insert

后端 未结 4 1716
半阙折子戏
半阙折子戏 2020-12-06 19:44

The following code should insert each key-value pair in an array into a mathing column-value in a table. The script returns no errors but the the inserted row contains only

4条回答
  •  一整个雨季
    2020-12-06 20:47

    Forget about bindParam, just use execute and pass it the values of $array:

    $STH->execute($array);
    

    Alternatively, you could scratch the named parameters altogether to simplify your code a little:

    $columnString = implode(',', array_keys($array));
    $valueString = implode(',', array_fill(0, count($array), '?'));
    
    $STH = $core->dbh->prepare("INSERT INTO table ({$columnString}) VALUES ({$valueString})");
    $STH->execute(array_values($array));
    

提交回复
热议问题