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

使用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');
  • 写回答

2条回答 默认 最新

  • 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?