1

Merely due to the sake of being efficient I would like to hear some advises from the PHP expers here. (Actually this question goes out all developers that mess with database connections on a regular basis)

Assume you have one personId and this id has multiple numbers. You have a table with columns pID,nums

From the php side you retrieve these numbers in an array. Now my question comes to place. Do you do something like;

for($i=0;$i<count($arr);$i++)
{
   //Call the insert query over and over again
}

Or there is obviously a better solution?

2 Answers 2

2

Essentially you want to do a bulk insert - it's faster to execute one composite statement, than lots of individual inserts, so try:

$data is your array
$sql = array(); 
foreach( $data as $row ) {
    $sql[] = '("'.mysql_real_escape_string($row['field1']).'")';
}
mysql_query('INSERT INTO table (field) VALUES '.implode(',', $sql));
Sign up to request clarification or add additional context in comments.

1 Comment

I assumed the tag implied it's MySQL :)
1

If your data set is really large, you can look at dumping your values into a file, and then executing "LOAD DATA INFILE" (will only work if MySQL runs on the same host as your script).

Alternatively, you can use one insert query:

INSERT INTO table(pid,nums) VALUES (1,2), (1,3), (1,4), ... -- etc

with multiple values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.