article

Monday, June 27, 2022

PHP MySQLi Upload Multiple Files

PHP MySQLi Upload Multiple Files

Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

CREATE TABLE `photo` (
  `photoid` INT(11) NOT NULL AUTO_INCREMENT,
  `location` VARCHAR(150) NOT NULL,
PRIMARY KEY(`photoid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
index.php
//index.php
<!DOCTYPE html>
<html>
<head>
	<title>PHP MySQLi Upload Multiple Files</title>
	<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
	<div class="row">
		<span style="font-size:25px; color:blue"><center><strong>PHP MySQLi Upload Multiple Files</strong></center></span>
		<hr> <br/>		
		<form method="POST" action="upload.php" enctype="multipart/form-data">
		<input class="form-control form-control-lg" id="formFileLg" type="file" name="upload[]" multiple>
		<br/>
		<input type="submit" value="Upload" class="btn btn-primary mb-3"> 
		</form>
	</div>
	<div class="row">
		<h2>Output:</h2>
		<?php
			include('conn.php');
			$query=mysqli_query($conn,"select * from photo");
			while($row=mysqli_fetch_array($query)){
				?>
				<div class="col-lg-3 col-md-4 col-6">
				  <a href="#" class="d-block mb-4 h-100">
					<img class="img-fluid img-thumbnail" src="<?php echo $row['location']; ?>" alt="">
				  </a>
				</div>
				<?php
			}
 
		?>
	</div>
</body>
</html>
conn.php
//conn.php
<?php
$conn = mysqli_connect("localhost","root","","devprojectdb");
if (!$conn) {
	die("Connection failed: " . mysqli_connect_error());
}
?>
upload.php
//upload.php
<?php
	include('conn.php');
 
	foreach ($_FILES['upload']['name'] as $key => $name){
 
		$newFilename = time() . "_" . $name;
		move_uploaded_file($_FILES['upload']['tmp_name'][$key], 'upload/' . $newFilename);
		$location = 'upload/' . $newFilename;
 
		mysqli_query($conn,"insert into photo (location) values ('$location')");
	}
	header('location:index.php');
?>

Related Post