Jump to content

Entering each array value into DB


AXiSS

Recommended Posts

I need to enter an array of values into a database, having each value be inserted as it's own row. I've searched for how to do it and the best I found was the foreach() function. So, would:

 

foreach ($array as value) {
  $result = mysql_query("INSERT INTO some_table (value1, value2) VALUES ('$value', '$someOtherValue')");
}

 

work, or is there a better way to do it?

Link to comment
Share on other sites

alternatively, you could do it in one mysql_query():

 

$sql = "INSERT INTO some_table (value1, value2) VALUES ";
$num_vals = count($array);
$i = 0;
foreach ($array as $value) {
  $i++;
  $sql .= "('$value', '$someOtherValue') ";
  if ($i < $num_vals) {
     $sql .= ", ";
  }
}
mysql_query($sql) or die(mysql_error());

 

not nearly as pretty...

Link to comment
Share on other sites

One of the main problems you want resolved is efficiency, that above foreach code works, provided you clear off the memory of the query each time:

 

foreach ($array as value) {
  $result = mysql_query("INSERT INTO some_table (value1, value2) VALUES ('$value', '$someOtherValue')");
  mysql_free_result($result);
}

 

This will run the query, clear off the memory of the query, making it more efficient, faster, and less straing on the server.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.