Jump to content

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/241580-loading-data-into-mysql-with-arrays/
Share on other sites

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.

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));

    };

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.