Question

I have a form that includes 4 text fields and multiple file upload (5 files/fields):

The database table has 9 fields, 4 for the text fields and the remaining 5 should hold a URL path to the images being uploaded by the form, for the 5 URL fields in the database they are simply named as image1, image2, image3…

Normally we collect the form data and do whatever MySQL query we need to insert or update, but I cant figure out how to assign the foreach loop results to a progressive/dynamic variable name so that after the iterations I am only doing 1 MySQL query/insert.

$inum=0;

foreach ($_FILES["prodi"]["error"] as $key => $error)
{
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["prodi"]["tmp_name"][$key];
        $name = $_FILES["prodi"]["name"][$key];
        $type = $_FILES["prodi"] ["type"] [$key];
        if ($type=="image/jpg" OR $type=="image/jpeg" OR $type=="image/pjpeg" OR $type=="image/png")
        {move_uploaded_file($tmp_name, "../zzz/zzz-images/$name");
        $ipath=$domain."/zzz/zzz-images/".$name;
        $inum++;
        $i="image".$inum; // STUCK AT THIS POINT //}
}

So, if i were to echo $i and $ipath inside the loop, i will get:

image1 (The table field storing the url)  /  *ttp://www.whaterver......(the url stored)

image2 (The table field storing the url)  /  *ttp://www.whaterver......(the url stored)

And so on until there are no more files in the array to process, but how do i set each loop result to a new variable so that the mysqli query works like this:

mysqli_query($con,"INSERT INTO `table1` (`field1`,`field2`,`field3`,`field4`,`image1`,`image2`,`image3`,`image4`,`image5`) VALUES ('field1',field2','field3','field4','loop_result1','loop_result2','loop_result3' etc. etc. etc.);")
Was it helpful?

Solution

With php you can use variables to create your variable names! So where you were stuck you should:

$varname  = "image".$inum; // "image1" for example
$$varname = $ipath; // this magic puts the value of $ipath into the variable $image1, $image2, etc

Here is an example of it working: https://eval.in/83538

OTHER TIPS

Try this:

$inum++;
${'image' . $inum} = $ipath; // STUCK AT THIS POINT //}
}

See : Dynamic variable names in PHP

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top