Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to insert array of data into mysql using php

Currently I have an Array that looks like the following when output thru print_r();

Array
(
    [0] => Array
        (
            [R_ID] => 32
            [email] => [email protected]
            [name] => Bob
        )

    [1] => Array
        (
            [R_ID] => 32
            [email] => [email protected]
            [name] => Dan
        )

    [2] => Array
        (
            [R_ID] => 32
            [email] => [email protected]
            [name] => Paul
        )

    [3] => Array
        (
            [R_ID] => 35
            [email] => [email protected]
            [name] => Mike
        )  
)

I would like to insert this data into one table with each element value belonging to its respective field.

Currently my php code looks like the following

if(is_array($EMailArr)){
    foreach($EMailArr as $R_ID => $email => $name){

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
    mysql_query($sql) or exit(mysql_error()); 
    }
}

*Note : R_ID is NOT the primary key in this table.*

Can someone help me understand how I should approach this situation? Thank you for reading and your help!

Regards.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I would avoid to do a query for each entry.

if(is_array($EMailArr)){

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";

    $valuesArr = array();
    foreach($EMailArr as $row){

        $R_ID = (int) $row['R_ID'];
        $email = mysql_real_escape_string( $row['email'] );
        $name = mysql_real_escape_string( $row['name'] );

        $valuesArr[] = "('$R_ID', '$email', '$name')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...