AXiSS Posted November 11, 2007 Share Posted November 11, 2007 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? Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted November 11, 2007 Share Posted November 11, 2007 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 Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted November 11, 2007 Share Posted November 11, 2007 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... Quote Link to comment Share on other sites More sharing options...
kratsg Posted November 11, 2007 Share Posted November 11, 2007 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.