本文介绍了使用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) {
}
?>
我要显示这样的数据
/*insert into tblname($key)values($value);
finally the query will appear correctly format */
insert into tblname('fname','lname') values('joe','sina');
推荐答案
请按照以下步骤操作:-
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);"
?>
现在查询将如下所示:- https://eval.in/854152
Now query will look like this:-https://eval.in/854152
注意:-
Note:-
上面的代码可以工作,但是我建议您使用prepared statements
来防止SQL Injection
.谢谢
The above code will work but I will suggest you to use prepared statements
to prevent from SQL Injection
.Thanks
帮助参考:-
Reference for help:-
这篇关于使用PDO插入具有关联数组的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!