duanke0555 2016-10-07 21:51
浏览 101
已采纳

将PHP关联数组映射到PDO预处理语句中

I'm doing some cleanup and transformation on data (that part is done, whew), and need to insert it into a MySQL table. Having done this kind of thing in Perl previously, I assumed that, as part of processing, it would make sense for me to structure the data as an associative array with the keys being the same as the field names I need to load them into - that way, it would be easy to construct a prepared statement simply by looping over the keys and producing a list of both the named placeholders and the matching values.

However, I can't seem to make this work in PHP/PDO. Test code:

$x = <<<EOD
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
EOD;

$fields = array('name', 'job', 'wallet_size', 'inseam', 'pet_name');
foreach(explode("
", $x) as $line){
    $data = array_combine($fields, explode(' ', $line));

    # print_r($data);

    $stmt = $dbh->prepare('INSERT INTO foobar VALUES('.':'.implode(', :', $fields));

    foreach($fields as $field){
        $stmt->bindParam(':'.$field, $data[$field]);
    }
    $stmt->execute();
}

Frankly, it feels too... graceless and hacky to work - and it doesn't.

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1' in tst.php:24

There is a correct way to do this, right? I'd appreciate it if someone would introduce me to the appropriate PHP-flavored phrasing for it.

  • 写回答

1条回答 默认 最新

  • doutuan8887 2016-10-07 21:58
    关注

    It's hard to debug SQL when you're staring at the PHP code that formats SQL, instead of the final SQL string itself. I suggest you always create a string variable so you can output it during debugging.

    $sql = 'INSERT INTO foobar VALUES('.':'.implode(', :', $fields);
    echo "$sql
    ";
    $stmt = $dbh->prepare($sql);
    

    Outputs:

    INSERT INTO foobar VALUES(:name, :job, :wallet_size, :inseam, :pet_name
    

    Now it's very easy to see that you forgot the closing ) at the end of that INSERT statement!

    Also, your use of PDO is more difficult than it needs to be. You don't need to use named parameters. You don't need to use bindParam(). Here's how I would write this code:

    $fields = array('name', 'job', 'wallet_size', 'inseam', 'pet_name');
    
    $columns = implode(',', $fields);
    $placeholders = implode(',', array_fill(1, count($fields), '?'));
    $sql = "INSERT INTO foobar ($columns) VALUES ($placeholders)";
    echo "$sql
    "; // use this during debugging
    $stmt = $dbh->prepare($sql);
    
    foreach(explode("
    ", $x) as $line){
        $param_values = explode(' ', $line);
        $stmt->execute($param_values);
    }
    

    Tips:

    • Prepare the query once, and re-use the prepared statement for each row of data you want to insert.
    • Pass an array of data values as an argument to execute(). This is easier than using bindParam().
    • Use positional parameter placeholders (?) instead of named parameter placeholders when your data is in a simple array instead of an associative array.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵