I want to upload multiple image using PDO in one row with comma separation, however I can only able to insert one image to database but in the upload directory all selected files are moved. How to do it?
<?php
for($x=0; $x<count($_FILES['pic']['tmp_name']); $x++ ) {
$file_name = $_FILES['pic']['name'][$x];
$file_size = $_FILES['pic']['size'][$x];
$file_tmp = $_FILES['pic']['tmp_name'][$x];
$t = explode(".", $file_name);
$t1 = end($t);
$file_ext = strtolower(end($t));
$ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");
if(in_array($file_ext, $ext_boleh)) {
$dir = 'uploads/';
$sumber = $file_tmp;
move_uploaded_file($sumber, $dir.$file_name);
$sql2 = "UPDATE project_detail SET pic = :pic WHERE no = '$no'";
$statement1 = $connection->prepare($sql2);
if ($statement1->execute([':pic' => $file_name])){ ?>
<script>
alert("new record uploded successfully");
window.location.href=('project.php');
</script>
<?php }
}else {
echo "Only Images can be store!";
}
}
?>
If I've understood correctly ( though I'm still confused by the update
satement rather than an insert
statement ) then a little re-writing to perform all the upload actions before trying to write to the db should work.
<?php
$images=[];
for( $x=0; $x < count( $_FILES['pic']['tmp_name'] ); $x++ ) {
$file_name = $_FILES['pic']['name'][$x];
$file_size = $_FILES['pic']['size'][$x];
$file_tmp = $_FILES['pic']['tmp_name'][$x];
/* Less complicated and more reliable method to find the file extension!! */
$file_ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
$ext_boleh = array( 'jpg', 'jpeg', 'png', 'gif', 'bmp' );
if( in_array( $file_ext, $ext_boleh ) ) {
$dir = 'uploads/';
$status = move_uploaded_file( $file_tmp, $dir . $file_name );
/*
if the file was moved OK then add it's name
to the images array - this will be used in
the sql later...
*/
if( $status )$images[]=$file_name;
}
}
/*
Where does `$no` come from?
Construct update ( or insert? ) sql statement
making sure we do not leave potential injection
possibilities....!
*/
$sql2 = 'UPDATE `project_detail` SET `pic` = :pic WHERE `no` = :no';
$statement1 = $connection->prepare( $sql2 );
/* Concatenate the image names into a comma separated string */
$args = array(
':pic' => implode(',', $images ),
':no' => $no
);
$result = $statement1->execute( $args );
if( $result ){
/* do a happy dance */
} else {
/* weep */
}
?>