Kamanda
Kamanda

Reputation: 305

How to upload an Image onto localhost server whilst path is stored in mysql database?

I was using this tutorial http://www.onlinebuff.com/article_step-by-step-to-upload-an-image-and-store-in-database-using-php_40.html to build up the code I have now. I'm also quite new to php so I had problems correcting some of his errors.

I tried to store images in the database and read them from there but what I want to do with them later will not allow me to do so, well it will be very difficult to monitor. The students will upload images onto the website and I'd like to monitor what they add up so that if someone does report the image i can then take it down easily. Therefore I have decided to use the file access route

I'd like to upload the image to the server and shortly after when the path is in the database i'd like to display it in, but right now my main concern is getting the file onto the server and the image path into the database.

When I run the php Code I get the error. I don't know why either.

Here is my php Code :

    <?php
    $con = mysqli_connect('localhost', 'root', 'root', 'koleesy');
    if (mysqli_connect_errno()) // Check connection
          {   echo "Failed to connect to MySQL: " . mysqli_connect_error();  }
    $dirpath = dirname(getcwd());

        function GetImageExtension($imagetype)
         {
           if(empty($imagetype)) return false;
           switch($imagetype)
           {
               case 'image/bmp': return '.bmp';
               case 'image/gif': return '.gif';
               case 'image/jpeg': return '.jpg';
               case 'image/png': return '.png';
               default: return false;
           }
         }



if (!empty($_FILES["uploadedimage"]["name"])) {

    $file_name=$_FILES["uploadedimage"]["name"];
    $temp_name=$_FILES["uploadedimage"]["tmp_name"];
    $imgtype=$_FILES["uploadedimage"]["type"];
    $ext= GetImageExtension($imgtype);
    $imagename=date("d-m-Y")."-".time().$ext;
    $target_path = $dirpath.$imagename;


if(move_uploaded_file($temp_name, $target_path)) {

    $Imageup="INSERT into 'images_tbl' ('images_path','submission_date') VALUES 

('".$target_path."','".date("Y-m-d")."')";
    if ($con->query($Imageup) === TRUE) {
    echo "New record created successfully"; }


else{

   echo("Error While uploading image on the server");
}
}
}
?>

Here is the index file where i'm testing it. Just an upload button and choose file.

<html lang="en">
<head>
    <title>Uploading Image to Folder Test</title>
</head>
<body>
    <form action="saveimage.php" enctype="multipart/form-data" method="post">

<table style="border-collapse: collapse; font: 12px Tahoma;" border="1" cellspacing="5" cellpadding="5">
<tbody><tr>
<td>
<input name="uploadedimage" type="file">
</td>

</tr>

<tr>
<td>
<input name="Upload Now" type="submit" value="Upload Image">
</td>
</tr>


</tbody></table>

</form>
</body>
</html>

I've looked at other examples but they all look very different. They use public void and stuff. Dunno what that is.

This is a picture of his table but mine looks relatively the same

Upvotes: 1

Views: 11720

Answers (1)

Jimmy Canadezo
Jimmy Canadezo

Reputation: 161

I also had this problem - I did figure it out though. I'll do a quick walk-through of how to upload a file to a directory, and save the path into MySQL, you can do multiple queries after you see the initial query, that way you can drop and delete the file as you wish. Here Goes:

picture_upload.php

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:<br>

    <input type="file" name="fileToUpload" id="fileToUpload"><br><br>


    <input type="submit" value="Upload Image" name="submit">
</form>

upload.php

    <?php $target_dir = "ANY_DIRECTORY_YOU_LIKE/PICTURES/";
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    // Check if image file is a actual image or fake image
    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
    }
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    // Check file size
    if ($_FILES["fileToUpload"]["size"] > 1000000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }
    // Allow certain file formats
    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
            $pictureName = "ANY_DIRECTORY_YOU_LIKE/PICTURES/". basename( $_FILES["fileToUpload"]["name"]);



$servername = "localhost";
$username = "MySQL_USERNAME";
$password = "MySQL_PASSWORD";
$dbname = "MySQL_DATABASE_NAME";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "UPDATE TableName SET myPicture='$pictureName' WHERE email='$myEmail' AND password='$myPassword'";
// Make Sure to tell MySQL which user you want to update which means setting the variable $myEmail and $myPassword accordingly

if ($conn->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error updating record: " . $conn->error;
}

$conn->close();





    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

Have Fun! Oh, and my Database is using VarChar for pictures. If you want to get creative and figure out another way - go ahead.

Upvotes: 4

Related Questions