数组插入mysql,如何将数组值插入mysql数据库?

本文介绍了一个PHP初学者如何将多维数组中的数据插入到MySQL数据库的方法。通过使用循环和手工构造SQL查询语句来实现这一过程,并提供了防止SQL注入攻击的基本措施。

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值