我正在做一些清理和数据转换(该部分完成,哇),并需要将其插入到MySQL表中。之前在Perl中完成了这种事情之后,我认为,作为处理的一部分,将数据作为关联数组来构造是有意义的,关键字与我需要将它们加载到的字段名相同 - 这样一来,只需循环遍历键并生成一个既有名称占位符又有匹配值的列表,就可以轻松构建一条准备好的语句。将PHP关联数组映射到PDO准备语句
但是,我似乎无法在PHP/PDO中完成这项工作。测试代码:
$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("\n", $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();
}
坦率地说,感觉太...粗俗和哈克工作 - 而事实并非如此。
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
有是这样做正确的方式,正确的?如果有人会向我介绍适合它的PHP风格的措辞,我会很感激。
是否尝试打印“'INSERT INTO foobar VALUES('。':'。implode(',:',$ fields)'?看起来你只是错过了关闭”)“''INSERT INTO foobar VALUES ('。':'。implode(',:',$ fields)。')'' –
@E_p - 干得好!我*做了*回应 - “内部”部分,而不是整个事情 - 它看起来不错。你是对的,这是最后的结果。 –