litebearer Posted May 13, 2010 Share Posted May 13, 2010 Have 2 arrays and am attempting to insert them into a table. The new rows are created BUT they only contain the non-array variables my code... $count1 = count($large_images); $query = "INSERT INTO images (image, thumb, when_up, who) VALUES ('$large_images[$i]', '$small_images[$i]', '$when_up', '$by_who')"; $i=0; while($i<$count1) { mysql_query($query); $i++; } ides?? Quote Link to comment Share on other sites More sharing options...
Asheeown Posted May 13, 2010 Share Posted May 13, 2010 $count1 = count($large_images); $i=0; while($i<$count1) { mysql_query("INSERT INTO images (image, thumb, when_up, who) VALUES (" . $large_images[$i] . ", " . $small_images[$i] . ", '$when_up', '$by_who')"); $i++; } That should work just fine Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted May 13, 2010 Share Posted May 13, 2010 Your $query variable is assigned a value, once, which is both before $i has been defined and it is before the loop. The while(){} loop just keeps using the same string that $query was assigned. You need to put the $query = "...." assignment statement inside of the loop if you want it to be evaluated with different values of $i. Quote Link to comment Share on other sites More sharing options...
litebearer Posted May 13, 2010 Author Share Posted May 13, 2010 a little tweaking worked... $i=0; while($i<$count1) { $query = "INSERT INTO images (image, thumb, when_up, who) VALUES ('" . $large_images[$i] . "', '" . $small_images[$i] . "', '$when_up', '$by_who')"; mysql_query($query); $i++; } Thank you Quote Link to comment Share on other sites More sharing options...
Psycho Posted May 13, 2010 Share Posted May 13, 2010 Do NOT do queries within loops. It creates a huge overhead on the server. You can process multiple inserts in a single query in the format INSERT INTO table (fieldA, fieldB, fieldC) VALUES ('val-1A', 'val-1B', 'val-1C'), ('val-2A', 'val-2B', 'val-2C'), ('val-3A', 'val-3B', 'val-3C') For your purposes: $count1 = count($large_images); //Create array of value statements $values = array(); for($i=0; $i<$count1; $i++) { $values[] = "('{$large_images[$i]}', '{$small_images[$i]}', '{$when_up}', '{$by_who}')"; } //Create single query to perform all inserts $query = "INSERT INTO images (image, thumb, when_up, who) VALUES " . implode(', ', $values); mysql_query($query); 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.