I made an upload file code without prepared statements. The file is successfully uploaded. But when I add prepared statements to the code, the contents of the file is not uploaded. Only the file name, size and type and uploaded in the database.
This is the code:
PHP:
<?php
include("config.php");
error_reporting( ~E_NOTICE );
if(isset($_POST['submit']) ){
//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
$allowed = array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext, $allowed)){
if($filesize < 2000000) {
//$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')"; <- old code line
$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES (?,?,?,?)";
$stmt = $con->prepare($query);
$stmt->bind_param("sbsi", $filename, $filedata, $filetype,$filesize);
$stmt->execute();
if ($stmt->errno){
echo "FAILURE!!! " . $stmt->error;
} else {
echo "<br>Inserted";
}
$stmt->close();
/* if ($con->query($query) === TRUE) <- old code line
{
echo "Uploaded<br>";
} else {
echo "Error! <br>" . $con->error;
} */
} else {
$errorMsg = "Sorry, your file is too large. Only 2MB is allowed";
}
}else{
$errorMsg = "Sorry, only zip, rar, pdf, doc & docx are allowed.";
}
//if user has no file to upload then proceed to this else statement
} else {
$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);
//$query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')"; <- old code line
$query = "INSERT INTO contracts(`filename`,`filetype`,`filesize`) VALUES (?,?,?)";
$stmt = $con->prepare($query);
$stmt->bind_param("ssi", $filename, $filetype,$filesize);
$stmt->execute();
if ($stmt->errno){
echo "FAILURE!!! " . $stmt->error;
} else {
echo "<br>Inserted";
}
$stmt->close();
/* if ($con->query($query) === TRUE) <- old code line
{
echo "Uploaded<br>";
} else {
echo "Error! <br>" . $con->error;
} */
}
$con->close();
}
?>
HTML:
<html><head></head>
<body>
<form method="post" action="" enctype="multipart/form-data">
<?php echo $errorMsg; ?>
Upload File:
<input type="file" name="upload" /><br>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>
Why is the contents of the file is not uploaded and missing in the database with prepared statements? What is wrong with my code?