Jump to content

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/201655-inserting-array-values-into-a-db-table/
Share on other sites

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.

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

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

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.