Upload and Show Image Using PHP/MYSQL

0
302

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 `photos` ( `photo_id` int(11) NOT NULL, `photo_link` text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

On the index page, put the following codes.

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

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

  1. <?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->query("INSERT INTO photos (photo_link) VALUES ('$img_link')") or die($mysqli->error);
  8. if ($upload) {
  9. header("Location: index.php?upload_action=success");
  10. } else if (!$upload) {
  11. echo $mysqli->error;
  12. }
  13. } else if ($_FILES['photo']['name'] == null) {
  14. echo 'Please choose a photo.';
  15. }
  16. ?>

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
(Visited 324 times, 1 visits today)

LEAVE A REPLY

Please enter your comment!
Please enter your name here