Can't store a .pdf file in a blob in mySQL - php

So I am trying to upload a PDF file into a mySQL blob, the table row gets inserted but in the fileContent which is the mediumBlob type it appears always as [BLOB 0 B] and when the file is downloaded, it is downloaded with 0 bytes. Ive echoed $content and it shows the special characters of the pdf file.
$erro = '';
$tipo = '';
if (isset($_POST['submit']) && isset($_POST['text']) && $_POST['text'] !== null && isset($_POST['userID']))
{
if(preg_match('/^[a-z0-9-]+$/',$_POST['text']) && strlen($_POST['text']) < 15 )
{
if (substr($_FILES['file']['name'], -3, 3) == "pdf" && $_FILES["file"]["size"] < 1000000)
{
if ($_FILES["file"]["error"] > 0)
{
$erro = "Problema: " . $_FILES["file"]["error"];
$tipo = 'erro';
}
else
{
$_FILES["file"]["name"] = $_POST['text'].'.pdf';
$erro = "Ficheiro guardado com sucesso.";
$tipo = 'sucesso';
}
}
else
{
$erro = "Apenas .PDF com menos de 10 Mb são permitidos!";
$tipo = 'erro';
}
}
else
{
$erro = "Nome inválido";
$tipo = 'erro';
}
if ($tipo == 'sucesso')
{
$content = $db->real_escape_string(file_get_contents($_FILES['file']['tmp_name']));
if ($_FILES["file"]["size"] > 0)
{
$smt = $db->prepare('INSERT into uploads (userRefID,fileName,fileType,fileSize,fileContent,uploadDate) values(?,?,?,?,?,?)');
$smt->bind_param('issibs', $_POST['userID'], $_FILES["file"]["name"], $_FILES["file"]["type"], $_FILES["file"]["size"], $content ,date(c));
$smt->execute();
$smt->close();
}
}
}
What am I doing wrong?

According to this comment you should not pass the blob directly in bind_param, but with send_long_data.
From the documentation of send_long_data here's an example:
$stmt = $mysqli->prepare("INSERT INTO messages (message) VALUES (?)");
$null = NULL;
$stmt->bind_param("b", $null);
$fp = fopen("messages.txt", "r");
while (!feof($fp)) {
$stmt->send_long_data(0, fread($fp, 8192));
}
fclose($fp);
$stmt->execute();

Related

SpreadSheet - Uncaught InvalidArgumentException: File "file.xlsx" does not exist

I am uploading an xlsx file in a folder and later reading it to insert the information into the database, however the spreadsheet plugin is not finding the file, it is going to a folder that does not make sense, below is code that I'm using.
The correct file path is: arquivosRetorno/file.xlsx
but he is looking for in PHP Fatal error: Uncaught InvalidArgumentException: File "file.xlsx" does not exist. in /vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Shared/File.php:137
$allowed_extension = array('xls', 'csv', 'xlsx');
$file_array = explode(".", $_FILES["arquivo"]["name"]);
$file_extension = end($file_array);
if(in_array($file_extension, $allowed_extension)){
$file_name = time() . '.' . $file_extension;
move_uploaded_file($_FILES['arquivo']['tmp_name'], 'arquivosRetorno/'.$file_name);
$file_type = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_name);
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($file_type);
$spreadsheet = $reader->load($file_name);
unlink($file_name);
$data = $spreadsheet->getActiveSheet()->toArray();
foreach($data as $row){
if($row[5] > 0){
$numeroIdentificacaoContribuicoes = $row[5];
$situacao = trim($row[7]);
$dataBaixaLiquidacao = trim($row[2]);
$dataPedacos = explode("/",$dataBaixaLiquidacao);
$dataBD = $dataPedacos[2]."-".$dataPedacos[1]."-".$dataPedacos[0];
if($row[5]>40107){
if ($numeroIdentificacaoContribuicoes != null || $numeroIdentificacaoContribuicoes != '') {
$bd->SQL = "SELECT * FROM entradas WHERE id2 = ".$numeroIdentificacaoContribuicoes;
$bd->Executa();
$status = $bd->Regs[0]["status"];
if ($situacao == 'Liquidado') {
if($status == "" || $status == "boleto nao foi pago" || $status == null){
$bd->SQL = "UPDATE entradas SET status = 'boleto pago', data_boleto = '".$dataBD."' WHERE id2 = ".$numeroIdentificacaoContribuicoes."";
$bd->Executa();
$bd2->SQL = "UPDATE transacoes SET status_transacao = '9995' WHERE numeropedido = ".$numeroIdentificacaoContribuicoes."";
$bd2->Executa();
}
}else{
if($status != "boleto pago"){
$bd->SQL = "UPDATE entradas SET status = 'boleto nao foi pago', data_boleto = '".$dataBD."' WHERE id2 = ".$numeroIdentificacaoContribuicoes."";
$bd->Executa();
echo "<br>";
echo $bd2->SQL = "UPDATE transacoes SET status_transacao = '9994' WHERE numeropedido = ".$numeroIdentificacaoContribuicoes."";
$bd2->Executa();
}
}
}
}
}
}
$message = '<div class="alert alert-success">Arquivo importado com sucesso</div>';
}else{
$message = '<div class="alert alert-danger">Apenas arquivos .xls .csv or .xlsx são aceitos</div>';
}
Change the call to:
$reader->load($file_name)
to:
$reader->load('arquivosRetorno/' . $file_name)

excel file upload to database using Php

I am trying to upload excel .xls file but got an error when I am trying to import autoload file my web page going blank and when I comment it its works. I can't Import file of spout extenstion of reader. Here this is my code.
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
require_once 'http://localhost/muddy/admin/spout-2.7.2/src/Spout/Autoloader/autoload.php';//Error cant import
here in this require once cant upload file if I write this code my web page going blank !
if (!empty($_FILES['file']['name'])) {
echo "ks";
$pathinfo = pathinfo($_FILES["file"]["name"]);
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['file']['size'] > 0 ) {
$inputFileName = $_FILES['file']['tmp_name'];
// Read excel file by using ReadFactory object.
$reader = ReaderFactory::create(Type::XLSX);
// Open file
$reader->open($inputFileName);
$count = 1;
foreach ($reader->getSheetIterator() as $sheet) {
echo "ks22";
// Number of Rows in Excel sheet
foreach ($sheet->getRowIterator() as $row) {
echo "ks32";
// It reads data after header. In the my excel sheet,
// header is in the first row.
if ($count > 1) {
echo "ks4";
// Data of excel sheet
$data['Member_no'] = $row[0];
$data['Member_name'] = $row[1];
$data['Gender'] = $row[2];
$data['Club_name'] = $row[3];
$data['member_since'] = $row[4];
$data['Expiry_date'] = $row[3];
$member_no = $data['Member_no'];
$member_name = $data['Member_name'];
$gender = $data['Gender'];
$club_name = $data['Club_name'];
$member_since = $data['member_since'];
$expiry_date = $data['Expiry_date'];
$query="INSERT INTO `mmholdin_management`.`Club_member` (Member_no`, `Member_name`, `Gender`, `Club_name`, `member_since`, `Expiry_date`) VALUES ($member_no ,$member_name, $gender,$club_name,$member_since,$expiry_date)";
echo $query;
if(mysql_query($query))
{
$msg = "Record Saved!";
//header("Location:managecustomer.php");
exit;
}
else
{
$msg = "Unable to Save!";
}
print_r(data);
}
$count++;
}
}
// Close excel file
$reader->close();
} else {
echo "Please Select Valid Excel File";
}
} else {
//echo "Please Select Excel File";
}
try this example.
$file = "your-file.xls";
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];
$sql = mysql_query("INSERT INTO xls (name, email) VALUES ('$name','$email')");
}
if($sql){
echo "You database has imported successfully";
}else{
echo "Sorry! There is some problem.";
}
check this: https://www.studytutorial.in/how-to-upload-or-import-an-excel-file-into-mysql-database-using-spout-library-using-php

How to upload excel file to mysql in php

I am trying to upload an excel file using the HTML input tag, to MySQL database using PHP. But the result is a whole lot of characters in the database. the only time it works correctly is when I create a .csv file with notepad and upload it.
if(isset($_POST['submit_excel'])){
if(!is_uploaded_file($_FILES['file_excel']['tmp_name'])){
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup_no_f").style.visibility = "hidden"; } document.getElementById("popup_no_f").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
} else {
$filename = $_FILES['file_excel']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if ($extension == 'xlsx' || $extension == 'csv' || $extension == 'xls') {
if($_FILES['file_excel']["size"] > 0)
{
$handle = fopen($_FILES['file_excel']['tmp_name'], "r");
$count = 0;
while (($data = fgetcsv($handle, 1024, ",")) !== FALSE)
{
$count++;
if ($count>1) {
if (empty(data[0]) && empty(data[1]) && empty(data[2]) && empty(data[3]) && empty(data[4]) ){
echo alert();
}else{
do{
$bookuniqueid = uniqueid();
$query = "SELECT book_unique_id FROM books_tbl WHERE book_unique_id= '$bookuniqueid' ";
$query_run = mysqli_query($link, $query);
$numRowsCheck = mysqli_num_rows($query_run);
} while ( $numRowsCheck > 0);
$import ="INSERT INTO books_tbl (book_name, book_authors, book_category, book_quantity, book_cd, book_unique_id, book_uploaded_admin, book_created_date, book_quant_stat) VALUES ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]', '$bookuniqueid', '$adminname', current_date, '$data[3]' )";
mysqli_query($link, $import);
}
}
}
fclose($handle);
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup").style.visibility = "hidden"; } document.getElementById("popup").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
}
} else {
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup_ext").style.visibility = "hidden"; } document.getElementById("popup_ext").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
}
}

You have an error in your SQL syntax error message when inserting record

I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";

MYSQL, PHP, image upload/update fail

i am trying to allow users to update their profile picture using this code.
require("../connection.php");
$imgName = $_FILES['pic']['name'];
$imgTmp = $_FILES['pic']['tmp_name'];
$imgtype = $_FILES['pic']['type'];
$imgSize = $_FILES['pic']['size'];
$maxFileSize = 200000;
$pic = "../uploads/" . $user_id . "_" . time() . $imgName;
if ($imgSize > $maxFileSize) {
$error = "size";
}
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$error .= "";
} else {
$error = "type";
}
if (file_exists($pic)) {
$error = "exists";
}
if ($error == "" && $imgName != "") {
move_uploaded_file($imgTmp, $pic);
mysql_query("UPDATE users SET pic = '$pic', WHERE username = '$username'");
if (!mysql_query($query, $connect)) {
die(mysql_error());
} else {
mysql_close($connect);
header('location:http://www.WEBSITE.co.uk/users/upload-pic-thanks.php');
}
} else {
header("Location:edit-pic-error.php?e=".$error);
}
and it gives me this in the address bar: edit-pic-error.php?e=type, however the file i am trying to upload is .jpg, and its smaller than the 20000kb allowance.
The table in my mysql database is called 'users', and the table row is called 'pic', its Varchar, 60, allow null ticked.
The table is not being updated with the new time stamped profile picture.
Please help.
Thanks very much
$imgtype = $_FILES['pic']['type'];
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$imgType vs. $imgtype, notice the case.

Categories