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

Archived

This topic is now archived and is closed to further replies.

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