I’m trying to store pdf files in the db using mysql blob and it always shows as 0 bytes if I use mysqli but it works fine with pdo
just for test purpose I added the database connection in the same file
<form action="submit_pdo.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<div class="formgroup container-fluid">
<label for="project_name">Project Name</label>
<input type="text" name="project_name" id="project_name"/>
</div>
<div class="formgroup container-fluid">
<input type="file" name="pdf_file" accept=".pdf"/> </div>
<br>
<div class="formgroup container-fluid">
<input type="submit" name="submit" value="Submit To Database"/>
</div>
</form>
PDO
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// echo "<pre>";
// var_dump($_POST);
// var_dump($_FILES);
// echo "</pre>";
if ($_FILES['pdf_file']['error'] != 0) {
echo 'Something wrong with the file.';
}
$project_name = htmlspecialchars($_POST['project_name']);
$file_tmp = $_FILES['pdf_file']['tmp_name'];
$file_name = $_FILES['pdf_file']['name'];
$pdf_blob = fopen($file_tmp, 'rb');
if($pdf_blob === false) {
return false;
}
$dsn = "mysql:host=localhost;dbname=files_db;charset=utf8mb4";
$pdo = new PDO($dsn, "root", "");
$query = "INSERT INTO `files_tbl` (`project_name`, `file_name`) values (:name, :file)";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':name', $project_name, PDO::PARAM_STR);
$stmt->bindParam(':file', $pdf_blob, PDO::PARAM_LOB );
if($stmt->execute()) {
echo 'Information saved';
}
else {
echo 'Could not save information to the database';
}
}else {
header('Location: index.php');
}
mysqli
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// echo "<pre>";
// var_dump($_POST);
// var_dump($_FILES);
// echo "</pre>";
if ($_FILES['pdf_file']['error'] != 0) {
echo 'Something wrong with the file.';
}
$project_name = htmlspecialchars($_POST['project_name']);
$file_tmp = $_FILES['pdf_file']['tmp_name'];
$file_name = $_FILES['pdf_file']['name'];
$pdf_blob = fopen($file_tmp, 'rb');
if($pdf_blob === false) {
return false;
}
$db =new mysqli("localhost","root", '', "files_db");
$query = "INSERT INTO `files_tbl` (`project_name`, `file_name`)
values (?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param("sb", $project_name, $pdf_blob);
if($stmt->execute()) {
echo 'Information saved';
}
else {
echo 'Could not save information to the database';
}
}else {
header('Location: index.php');
}