Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

php - How to insert array value into mysql database?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...