View Full Version : For loop to add data into MySQL table?


Rockford
06-12-2005, 06:06 PM
Wonder if there's a way of doing this?

I'm looking to bulk add image URLs to the database - is there a way to do this by means of a for loop, or somesuch thing?

The image URLs are as follows:

img_001.jpg
img_002.jpg
...
...
img_081.jpg

Is there any way of automatically inserting into the table, without doing it the hard way?

Cheers.
A.

Harry Bo
06-12-2005, 06:41 PM
Er... well, there are loads really. You don't even mention what programming language you want to use, so that would be a start ;)

Ultimately it boils down to whether you want to do it as a single query (in which case you'd assemble a long string of input data and wrap it with a little SQL) or multiple queries (which is the method I'll demonstrate below).

PHP sample (untested):for ($i = 0; $i <= 99; $i++) {
$sql = "INSERT INTO table SET url='img_" . str_pad($i,3,"0",STR_PAD_LEFT) . ".jpg'";
$result = mysql_query($sql);
if ($result) {echo $i . " insertion succeeded
";} else {echo $i . " insertion failed
";}
}Obviously your SQL query is likely to involve more fields etc. Doing it all as one query would involve successively producing a larger SQL fragment (look at the alternate INSERT syntax), then adding a touch more SQL and executing it.

HTH :)

HB