Image upload using PHP and MySQL database

In this tutorial, we create a form that takes an image and some paragraphs. When you select an image and enters some text and clicks the submit button, the data is submitted to the server. Image upload using PHP and MySQL database

PHP now grabs the image and saves it in a folder in the project, and then saves the text in the database together with a link pointing to the image in the folder. Read about PHP

You can learn about more tutorials on PHP and ReactJs :

Now make a database with name img_upload and create a table called image with fields:

  • id – int(11)
  • image – varchar(100)
  • image_text – text
  // Create database connection
  $db = mysqli_connect("localhost", "root", "", "img_upload");

  // Initialize message variable
  $msg = "";

  // If upload button is clicked ...
  if (isset($_POST['upload'])) {
  	// Get image name
  	$image = $_FILES['image']['name'];
  	// Get text
  	$image_text = mysqli_real_escape_string($db, $_POST['image_text']);

  	// image file directory
  	$target = "images/".basename($image);

  	$sql = "INSERT INTO images (image, image_text) VALUES ('$image', '$image_text')";
  	// execute query
  	mysqli_query($db, $sql);

  	if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
  		$msg = "Image uploaded successfully";
  		$msg = "Failed to upload image";
  $result = mysqli_query($db, "SELECT * FROM images");
<!DOCTYPE html>
<title>Image Upload</title>
<style type="text/css">
   	width: 50%;
   	margin: 20px auto;
   	border: 1px solid #cbcbcb;
   	width: 50%;
   	margin: 20px auto;
   form div{
   	margin-top: 5px;
   	width: 80%;
   	padding: 5px;
   	margin: 15px auto;
   	border: 1px solid #cbcbcb;
   	content: "";
   	display: block;
   	clear: both;
   	float: left;
   	margin: 5px;
   	width: 300px;
   	height: 140px;
<div id="content">
    while ($row = mysqli_fetch_array($result)) {
      echo "<div id='img_div'>";
      	echo "<img src='images/".$row['image']."' >";
      	echo "<p>".$row['image_text']."</p>";
      echo "</div>";
  <form method="POST" action="index.php" enctype="multipart/form-data">
  	<input type="hidden" name="size" value="1000000">
  	  <input type="file" name="image">
      	placeholder="Say something about this image..."></textarea>
  		<button type="submit" name="upload">POST</button>

Now more tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *