in2d
in2d

Reputation: 638

Image doesn't appear on MYSQL database

My problem is that if i try to post a image trought my website to my database called photos they don't appear there. Images do appear inside the folder i created upload/img. My database photos table is called images with 2 rows. id int(11) and image MEDIUMBLOB. Any ideas why doesn't my images appear on my MYSQL database?

    <?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
  <title>Image Upload</title>
</head>
<body>
  <?php if(isset($_SESSION['err'])){ ?>
    <h2><?php echo $_SESSION['err']; ?></h2>
  <?php session_unset(); } ?>
  <form method="post" action="upload.php" enctype="multipart/form-data" >
    <input type="file" name="image" />
    <input type="submit" value="Submit" name="save">
  </form>
</body>
</html>

My upload.php

<?php

require_once('config.php');
session_start();
if(isset($_POST['save']))
{
  $target_dir = "upload/img/";
  $filename = explode('.',$_FILES['image']['name']);
  $ext = $filename[1];
  $imgname = time().'.'.$ext;
  $target_file = $target_dir . $imgname ;
 if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
      $path=$imgname;
      $conn->query("INSERT INTO images (id, image)VALUES ('$path')");
      $_SESSION["Success"]='Image Is Upload Success...';
      header("Location:view.php"); /* Redirect browser */
      exit();
    } else {
      $_SESSION["err"]=$text;
      header("Location:index.php"); /* Redirect browser */
      exit();
    }
  }
}

?>

Here is picture of my "images" table.

enter image description here

Upvotes: 1

Views: 1421

Answers (2)

in2d
in2d

Reputation: 638

So i figured it out why those pictures wont upload to my MYSQL database.

  1. Like some people here suggested i didn't need "id" written in my INSERT part.

  2. My table id row had to be set to primary and AUTO_INCREMENT(see image below).

enter image description here

Now things seem to be working fine. You can set image row type from varchar to blob.

Upvotes: 0

Rami
Rami

Reputation: 171

it has to be

if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
  $path=$imgname;
  $conn->query("INSERT INTO images (image) VALUES ('$path')");
  $_SESSION["Success"]='Image Is Upload Success...';
  header("Location:view.php"); /* Redirect browser */
  exit();
} else {
  $_SESSION["err"]=$text;
  header("Location:index.php"); /* Redirect browser */
  exit();
}

because you are telling Mysql to insert id but you didn't provide it's value

Upvotes: 1

Related Questions