Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store array contents in database

I have a php function getContactList():

$res = getContactList(trim($_POST['username']), trim($_POST['password']));

which returns this array:

$contactList[] = array('name' => $name, 'email' =>$email);

I need to store the contents of this array into a MySQL database. Somehow can i store the entire contents of the array in the database at one go ?? The number of array items will be more than 500 at each go , so i wanna avoid the usual looping practice and calling the "Insert" statement in the for loop as this will need a long time to execute.

Note: I need to store the results in separate columns - One for Name and another for Email. With 500 items in that array I need to have 500 rows inserted - one Name-Email pair per row.

like image 700
Sandy505 Avatar asked Dec 13 '22 08:12

Sandy505


1 Answers

$values = array();
// the above array stores strings such as:
// ('username', '[email protected]')
// ('o\'brien', '[email protected]')
// etc
foreach($contactList as $i => $contact) {
    $values[] = sprintf(
        "('%s', '%s')",
        mysql_real_escape_string($contact['name'], $an_open_mysql_connection_identifier),
        mysql_real_escape_string($contact['email'], $an_open_mysql_connection_identifier)
    );
}
$query = sprintf(
    "INSERT INTO that_table(name, email) VALUES %s",
    implode(",", $values)
);
like image 75
Salman A Avatar answered Dec 23 '22 12:12

Salman A