I'm beginner programming. I try to insert array value into mysql table.
here is my array:
$responseArray=Array
(
[0] => Array
(
[code] => 9BP3
[name] => 9Bp No3
)
[1] => Array
(
[code] => AA
[name] => Ataria
)
[2] => Array
(
[code] => AABH
[name] => Ambika Bhawani Halt
)
[3] => Array
(
[code] => AADR
[name] => Amb Andaura
)
[4] => Array
(
[code] => AAG
[name] => Angar
)
[5] => Array
(
[code] => AAH
[name] => Itehar
)
)
and here is mysql table structure:
id, code, name
How to insert array into this table using loop?
and If in database table row differ from array count then it will truncate table and insert array.
解决方案
Here is a very basic example making hand-crafted SQL queries:
$aValues = array();
// Don't forget to protect against SQL injection :)
foreach($responseArray as $row){
$aValues[] = '("'.$row['code'].'","'.$row['name'].'")';
}
$sql = 'INSERT INTO table (code, name) VALUES '.implode(',',$aValues).';';
But of course it all depends on what MySQL driver / DAL you might be using (e.g. PDO would be better to learn, but might be harder for a beginner).
本文介绍了一个PHP初学者如何将多维数组中的数据插入到MySQL数据库的方法。通过使用循环和手工构造SQL查询语句来实现这一过程,并提供了防止SQL注入攻击的基本措施。
299

被折叠的 条评论
为什么被折叠?



