Upload and Show Image Using PHP/MYSQL

0
339

In this tutorial about Upload and Show Image Using PHP/MYSQL, you will learn on how to upload an image in the database and show it in a page after uploading the image.

First, create a database and name it as any name you desire. Then create a table, name it as “photos“.

  1. CREATE TABLE <code>photos</code> ( <code>photo_id</code> int(11) NOT NULL, <code>photo_link</code> text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

On the index page, put the following codes.

  1. &lt;?php include 'connection.php'; ?&gt;
  2. &lt;!DOCTYPE html&gt;
  3. &lt;html&gt;
  4. &lt;head&gt;
  5. &lt;meta charset="UTF-8"&gt;
  6. &lt;title&gt;Upload Photo in PHP &amp; MYSQL&lt;/title&gt;
  7. &lt;/head&gt;
  8. &lt;body&gt;
  9. &lt;h3&gt;Upload and Show Photo in PHP &amp; MYSQL&lt;/h3&gt;
  10. &lt;?php
  11. if (isset($_GET['upload_action'])) {
  12. if ($_GET['upload_action'] == "success") { ?&gt;
  13. &lt;b&gt;Photo Successfully Uploaded&lt;/b&gt;
  14. &lt;?php }
  15. }
  16. ?&gt;
  17. &lt;form method="post" action="upload.php" enctype="multipart/form-data"&gt;
  18. &lt;label&gt;Choose Photo:&lt;/label&gt;&lt;br&gt;
  19. &lt;input type="file" name="photo" /&gt;&lt;br&gt;&lt;br&gt;
  20. &lt;input type="submit" value="Upload" /&gt;
  21. &lt;/form&gt;&lt;br&gt;
  22. &lt;?php
  23. $photos = $mysqli-&gt;query("SELECT * FROM photos");
  24. ?&gt;
  25. &lt;b&gt;&lt;?php echo $photos-&gt;num_rows ?&gt;&lt;/b&gt; total photos uploaded&lt;br&gt;&lt;br&gt;
  26. &lt;?php
  27. while ($photo_data = $photos-&gt;fetch_assoc()) { ?&gt;
  28. &lt;img src="&lt;?php echo $photo_data['photo_link']; ?&gt;" width="200px" height="200px" /&gt;
  29. &lt;?php }
  30. ?&gt;
  31. &lt;/body&gt;
  32. &lt;/html&gt;

Create an “upload.php” file then put the following codes.

  1. &lt;?php
  2. include 'connection.php';
  3. if ($_FILES['photo']['name'] != null) {
  4. move_uploaded_file($_FILES['photo']['tmp_name'], "images/" . $_FILES['photo']['name']);
  5. $img_link = "images/" . $_FILES['photo']['name'];
  6.  
  7. $upload = $mysqli-&gt;query("INSERT INTO photos (photo_link) VALUES ('$img_link')") or die($mysqli-&gt;error);
  8. if ($upload) {
  9. header("Location: index.php?upload_action=success");
  10. } else if (!$upload) {
  11. echo $mysqli-&gt;error;
  12. }
  13. } else if ($_FILES['photo']['name'] == null) {
  14. echo 'Please choose a photo.';
  15. }
  16. ?&gt;

Screenshot:

If you have any questions or suggestion about Upload and Show Image Using PHP/MYSQL, please feel free to contact us at our contact page.

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here