Jump to content

Inserting array values into a db table


litebearer

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.