Multiple image upload and insert into one row in database(MySQL) with comma separation in PDO

if(isset($_POST['mailSend'])){
$statement = $db->prepare("SHOW TABLE STATUS LIKE 'mail'");
$statement->execute();
$result = $statement->fetchAll();
	foreach($result as $row)
		$new_id = $row[10]; //10 fixed
$i=0;	
foreach ($_FILES['attached']['name'] as $up_filename) {
	$i++;
        //$up_filename=$_FILES["attached"]["name"];
	$file_basename = substr($up_filename, 0, strripos($up_filename, '.')); // strip extention
	$file_ext = substr($up_filename, strripos($up_filename, '.')); // strip name
	$f1 = $new_id .'-'.[$i]. $file_ext;
		
	if(($file_ext!='.png')&&($file_ext!='.jpg')&&($file_ext!='.jpeg')&&($file_ext!='.gif'))
		throw new Exception("Only jpg, jpeg, png and gif format images are allowed to upload.");
		
		move_uploaded_file($_FILES["attached"]["tmp_name"],"../uploads/mail/" . $f1);
	// End attached file
	}
        $statement = $db->prepare("INSERT INTO mail (orderNo,attached) VALUES (?,?)");
        $statement->execute(array($_POST['orderNo'],$f1));
}

and The HTML

<form id="" method="POST" action=""  enctype="multipart/form-data">
        <input type="text" name="orderNo">
	<input id="file-0" class="file" type="file" name="attached[]" multiple>
	<button class="btn btn-success " type="submit"  name="mailSend" >Send Mail</button>				
</form>

as I want to insert my Image like this :
So need help about this task.
Thanks

You need to create an array of the files names within the loop that processes the images and then outside of that loop submit the record to the database once with the array being written to the ‘attached’ field.

Is there a reason you want it all in one row? Is it not easier to manage in separate rows? If you want to delete a single row/image it will be easier separately.

1 Like

Surely it would be better to have a look-up table, not store multiple values in one column.

thanks

I’d agree, will make it very difficult to deal with later on. As they seem to be email attachments, though, it might not matter that removing one in the future will be much more complex than a simple query if they were stored in a separate table. As well as that, you need to have a much larger column size to cope with the maximum possible number of attachments that might be stored against a single mail, though I might be showiing my roots there in worrying about disk usage.

If you’re dead set on doing it in a single column, I’d modify the loop to keep appending the new filename to your list of filenames, then use that composite variable to call the query. Though maybe as @Noppy said above, you could build an array instead.

$f1 = $new_id . '-' . $i . $file_ext;
$flist .= $f1;
...
$statement->execute(array($_POST['orderNo'], $flist));

Also you need to sanitise the $_POST variables before you store them in the database.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.