如何将数组值插入mysql数据库? [英] How to insert array value into mysql database?

查看:476
本文介绍了如何将数组值插入mysql数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者.我尝试将数组值插入mysql表. 这是我的数组:

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

这是mysql表结构:

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.

推荐答案

以下是进行手工SQL查询的非常基本的示例:

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

但是,当然,这完全取决于您可能使用的MySQL驱动程序/DAL(例如,学习PDO更好,但对于初学者而言可能更难).

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

这篇关于如何将数组值插入mysql数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆