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.

图片转代码服务由CSDN问答提供 功能建议

我正在对数据进行一些清理和转换(该部分已完成,并且需要插入) 进入MySQL表。 之前在Perl中做过这种事情,我认为,作为处理的一部分,我将数据结构化为关联数组是合理的,其中键与我需要加载它们的字段名称相同 - 这样,只需循环键并生成命名占位符和匹配值的列表,就可以很容易地构造一个预准备语句。</ p>

然而,我似乎无法 使这个工作在PHP / PDO中。 测试代码:</ p>

  $ x =&lt;&lt;&lt; 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-&gt; prepare('INSERT INTO  foob​​ar VALUES('。':'。implode(',:',$ fields)); 
 
 foreach($ fields as $ field){
 $ stmt-&gt; bindParam(':'。$ field,  $ data [$ field]); 
} 
 $ stmt-&gt; execute(); 
} 
 </ code> </ pre> 
 
 

坦率地说,感觉太...... 没有工作的优雅和hacky - 它没有。</ p>

 致命错误:未捕获的异常'PDOException',消息'SQLSTATE [42000]:语法错误或访问冲突:1064你 您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以便在tst.php中使用“第1行”附近的正确语法:24 
 </ code> </ pre> 
 \  n 

是</ strong>正确的方法,对吗?我很感激 如果有人会为我介绍适当的PHP风格的措辞。</ p> </ div>

1条回答 默认 最新

相关推荐 更多相似问题