Forum Moderators: coopster
[codes] <?
$max_no_img=3; // Maximum number of images value to be set here
echo "<form method=post action=car.php enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='userfile[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
?>[codes]
car.php
[codes]
<?php
$username = "";
$password = "";
$database = "";
$hostname = "";
mysql_connect($hostname,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
for($i=0; $i < 3; $i++)
{
$ext = findexts ($_FILES['userfile']['name'][$i]) ;
$ran = rand () ;
$ran2 = $ran.".";
$add = "upload/";
$add = $add . $ran2.$ext;
$image[$i] = $ran2.$ext ;
move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $add);
$new_id = $image[$i]++;
$pic =$new_id++;
$query = "INSERT INTO table (image_name1,image_name2,image_name3)". "VALUES ('$ran.$ext','$new_id','$pic')";
mysql_query($query) or die('Database Query Error!');
}
echo "Successfully uploaded the image";
exit;
?>[codes]
Anyway the problem is that your insert is inside the for loop, use the loop only to compile the query string. You sort out what you want to do with the three fields.
for($i=0; $i < 3; $i++)
{
mysql_query($query) or die('Database Query Error!');
}
Which inserts it three times. Make your loop just for compiling the recursive part of the select for the images, insert once.
Do something like this, compile the query into a single select. I'm only using the $ran.$ext value because I'm not fully getting why you're adding the other data when you say you want to insert the images in just the one field.
$query = "INSERT INTO table (image_name1,image_name2,image_name3) values(";
for($i=0; $i < 3; $i++) {
$ext = findexts ($_FILES['userfile']['name'][$i]) ;
$ran = rand () ;
$ran2 = $ran.".";
$add = "upload/";
$add = $add . $ran2.$ext;
$image[$i] = $ran2.$ext ;
move_uploaded_file($_FILES['userfile']['tmp_name'][$i], $add);
$new_id = $image[$i]++;
$pic =$new_id++;
$query .= "'$ran.$ext',";
}
//Strip off last comma
$query = preg_replace('/,$/','',$query);
$query .= ')';
mysql_query($query) or die('Database Query Error!');