doumanju2533
doumanju2533
2017-09-02 12:01
浏览 160
已采纳

使用PDO使用关联数组插入数据

Before you duplicate your question, I read all answers that it's has a relation with my question. I'm trying to insert data with associative array for example

<?php 
$data = array(
         'fname'=>'joe',
         'lname'=>'sina'
);
foreach ($data as $key=>$value) {

}
?>

I want to display data like this

/*insert into tblname($key)values($value);
 finally the query will appear correctly format */
insert into tblname('fname','lname') values('joe','sina');

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

在复制问题之前,我会阅读所有与我的问题有关系的答案。 我正在尝试使用关联数组插入数据,例如

 &lt;?php 
 $ data = array(
'fname'=&gt;'joe',\  n'lname'=&gt;'sina'
); 
foreach($ data as $ key =&gt; $ value){
 
} 
?&gt; 
   \  n 
 

我想显示这样的数据

  / * insert to tblname($ key)values($ value); 
最后查询将正确显示 格式* / 
insert到tblname('fname','lname')值('joe','sina'); 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongshang1979
    dongshang1979 2017-09-02 12:10
    已采纳

    Do it like below:-

    <?php 
    $data = array(
             'fname'=>'joe',
             'lname'=>'sina'
    );
    
    $columns = "`".implode('`,`', array_keys($data))."`";
    $values = "'".implode("','", array_values($data))."'";
    
     //NOW CHANGE QUERY CODE LIKE BELOW
     //"INSERT INTO tblname($columns) values($values);" 
    ?>
    

    Now query will look like this:-https://eval.in/854152

    Note:-

    The above code will work but I will suggest you to use prepared statements to prevent from SQL Injection.Thanks

    Reference for help:-

    mysqli::prepare

    PDO::prepare

    点赞 评论
  • dounieqi6959
    dounieqi6959 2017-09-02 12:05

    You don't need to use foreach here. If you just prepare and bind the query, you can pass $data to the execute() and get the keys by implode() on the keys.

    $data = array(
             'fname'=>'joe',
             'lname'=>'sina'
    );
    $stmt = $pdo->prepare("INSERT INTO tblname (".implode(', ', array_keys($data)).") VALUES (:".implode(', :', array_keys($data)).")");
    $stmt->execute($data);
    

    The keys in the array must match the placeholders in the query (the ones with a colon in front of it). You also had a syntax error in the query, as columns cannot be quoted by singlequotes.

    点赞 评论

相关推荐