Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

inserting array into mysql

Status
Not open for further replies.

jimbojames5645

Programmer
Joined
Dec 12, 2003
Messages
36
Location
US
I need to insert a bunch of data into a mysql table from an array, but I don't want to use a bunch of queries. Is there any way to insert data from an array directly into mysql besides a loop?
 
You can do it by storing the entire array in a single table entry by storing in the table the output of serialize() ( against the array.

If you want one array element each in its own table row, you're going to have to loop somewhere.

You can loop through the array to create and execute an insert query for each element of the array.

You can also loop through the array to create a single compound insert statement:

Code:
$the_array = array ('foo', 'bar', 'baz);
$query = "INSERT INTO foo values ";
$first_element = TRUE;
foreach ($the_array as $value)
{
   if (!$first_element)
   {
      $query .= ", ";
   }

   $query .= "('" . $value . "')";
   $first_element = FALSE;
}

Should produce a query like:

INSERT INTO foo values ('foo'), ('bar'), ('baz')

Which will insert all three elements in one query.

Want the best answers? Ask the best questions: TANSTAAFL!!
 
My issue is timing-- I have found that the $str .= "blah" is costly. I am processing millions of records. So I need something that is fast, any recommendations?
 
sample record looks similar to this:
(email, fname, lname, address, city, state, zip)
 
I am taking data in table_x, checking to see if it exists in table_y. If it is not in table_y, then I want to insert the record into table_y.
 
then you can also use the left outer join function for that

insert into table_y(key_y,fieldy1,fieldy2) values
select key_x,fieldx1,fieldx2 from table_x left outer join table_y on key_x=key_y where key_y is null and key_x is not null

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top