chrxr Posted July 10, 2011 Share Posted July 10, 2011 Just trying to learn PHP and MySQL at the mo, and getting stuck on a really simple thing. I'm trying to populate MySQL table using a numeric array. Got a simple For loop to insert the data, but only the third of three rows is added to the table (Charly the 3yo Cheetah). The code is below: $family= array("Lion", "Cougar", "Cheetah"); $name= array("Leo", "Growler", "Charly"); $age= array(3, 4, 3); for ($j = 0; $j < 3; ++$j) { $query = "INSERT INTO cats VALUES(NULL, '$family[$j]', '$name[$j]', $age[$j])"; }; I'm sure it's blindingly obvious what's wrong, but I can't see it. Thanks! Quote Link to comment Share on other sites More sharing options...
per1os Posted July 10, 2011 Share Posted July 10, 2011 A few issues I saw. First up, you never call mysql_query. I am not sure if you do it later, but $query will get overwritten by the time you call it later. Second, the variables may not be being parsed correctly, array's can be funny inside of double quotes, so I find it best to use the { } around them so that you know they will get parsed properly. I also made it to use extended inserts, so you only have to make 1 mysql_query call, which will be way more efficient and less taxing on the mysql server. $family= array("Lion", "Cougar", "Cheetah"); $name= array("Leo", "Growler", "Charly"); $age= array(3, 4, 3); $cnt = count($family); $query = array(); for ($i=0; $i < $cnt; $i++) { $query[] = "(NULL, '{$family[$i]}', '{$name[$i]}', {$age[$i]})"; } $query = 'INSERT INTO cats VALUES ' . implode(',',$query) . ';'; mysql_query($query) or trigger_error('Error inserting: ' . mysql_error()); Questions let me know. Quote Link to comment Share on other sites More sharing options...
harristweed Posted July 10, 2011 Share Posted July 10, 2011 i assume that mysql_query($query)){ is outside your for loop therefore as you are aware only Cheetah Charly 3 are getting added try for ($j = 0; $j < 3; ++$j) { $query = "INSERT INTO cats VALUES(NULL, '$family[$j]', '$name[$j]', $age[$j])"; if(mysql_query($query)); }; Quote Link to comment Share on other sites More sharing options...
harristweed Posted July 10, 2011 Share Posted July 10, 2011 frost110's answer is much better than mine! Quote Link to comment Share on other sites More sharing options...
chrxr Posted July 10, 2011 Author Share Posted July 10, 2011 Took me a while to get my head around, but got it now. Thanks both! 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.