Jump to content

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
https://forums.phpfreaks.com/topic/76910-entering-each-array-value-into-db/
Share on other sites

Yeah, thats fine - you can only insert one row at a time anyway. Though it should be:

 

foreach ($array as $value)

 

Note the $ sign.

 

Also, your signiture should really read $AXiSS = $Graphic_Designer;, with a single equals sign. Unless it was deliberate of course ;)

 

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...

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.

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.