How to upload file in PHP and store information in SQLi database?

539 Views Asked by At

So I'm trying to do this file upload, and store information such as the size of the file, name, and URL of it in a database, while having the file just upload to a folder on my computer (for testing purposes). It's uploading no problem, the only issue I'm having is that the information I want isn't getting stored in the database.

if($_SERVER['REQUEST_METHOD']=='POST') {
$target_dir = "uploads/";
$file_name=basename($_FILES["fileToUpload"]["name"]);
$target_file = $target_dir . $file_name;
$fileSize=$_FILES["fileToUpload"]["size"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$complete=$file_name.$imageFileType;
$myUrl=$target_dir.$complete;

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
 // Check file size
if ($_FILES["fileToUpload"]["size"] > 10000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
 }
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "pdf" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only PDF, 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)) {
        $mysqli=connect();
        $stmt=$mysqli->prepare('INSERT INTO tbl_file (file_name,file_title,file_size,file_url) VALUES (?,?,?,?)') or die(mysqli_error());

        $stmt->execute();
        $stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl);
        $stmt->close();
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.<br>";

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

It has to be something with the SQL statement, but I just can't see what it is, any ideas?

2

There are 2 best solutions below

1
On BEST ANSWER

I see you have called the bindParameters() method after calling execute(). It should be the other way round.

i.e.

$stmt->bind_param('ssis',$complete,$file_name,$fileSize,$myUrl);
$stmt->execute();

...

0
On

I think maybe it's the reason that you used the incorrect method to open a new connection to the MySQL server.

You can create a new connection like this:

$mysqli=new mysqli("dbhost","username","passwd","dbname"); 

or

$mysqli=new mysqli();
$mysqli->connect("dbhost","username","passwd","dbname");

or

$connection = mysqli_connect("dbhost","username","passwd","dbname");

In addition,you must bind parameters firstly and then execute the sql.