How to upload image PHP and insert path in MySQL?

On your comment you ask how to upload and store the data to mysql. So here it is:

To get the file, you should have a script in your html like this:

<html>
<body>

     <form action="upload_file.php" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
     </form>

</body>
</html>

Now, on POST, your PHP file should look like this but please take note that you have to check if the file exists on your POST:

if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";
  echo "Type: " . $_FILES["file"]["type"] . "<br>";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];

  }

Since the “Stored in:” part is just the temporary path, you should move to your ‘real’ image path using move_uploaded_file().
Let say the real/default path for your images is in:

$image_dir="/images/";

You just have to move the file using this:

move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $image_dir. $_FILES['uploaded_file']['name']);

And your full path to the image would be

$image = $final_save_dir . $_FILES['uploaded_file']['name'];

There are several ways to store the path to your database:

1st: Is to store just the filename and concatenate the path of the image in PHP using $_SERVER['DOCUMENT_ROOT'] and your default image path like:

$sql="insert into employee_detail( emp_image, employee_name, employee_address,
    employee_contact, employee_designation, employee_salary) 
values( '$image', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
    '$_POST[employee_designation]','$_POST[employee_salary]')";

2nd: Is to store the full path like:

$sql="insert into employee_detail( emp_image, employee_name, employee_address,
    employee_contact, employee_designation, employee_salary) 
values( '".$_SERVER['DOCUMENT_ROOT']."\\images\\".$image."', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
    '$_POST[employee_designation]','$_POST[employee_salary]')";

What I recommend is this approach wherein you will input the partial path (without the root dir) so that later you don’t have a problem on deploying it:

$sql="insert into employee_detail( emp_image, employee_name, employee_address,
    employee_contact, employee_designation, employee_salary) 
values( 'images\\".$image."', '$_POST[employee_name]', '$_POST[employee_address]', '$_POST[employee_contact]',
    '$_POST[employee_designation]','$_POST[employee_salary]')";

And make sure that the images are successfully upload to that default image dir/path.

UPDATE

I also recommend that you use mysqli_* or PDO and use prepare() method /function to prevent sql injection.

Leave a Comment