How to upload excel file to mysql in php - 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>';
}
}

Related

Import CSV file with auto generate code to MySQL database

I just want to ask if how can I import a CSV file to MySQL database with an auto-generated QR code? I can now import CSV file to database however I can't make it work with the QR code.
Here's the working code for importing a CSV file.
$conn = getdb();
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE){
$sql = "INSERT into users (name)
values ('".$getData[0]."')";
$result = mysqli_query($conn, $sql);
if(!isset($result)){
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"ad-bulk.php\"
</script>";
} else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"ad-bulk.php\"
</script>";
}
}
fclose($file);
}
}
And this is the code that I'm using to generate a QR code. I already tried this code if my approach is to to add user one by one. However, I need to import a bulk of data.
$uniqueid = uniqid('IT-');
$text = $uniqueid;
$path = '../temp/';
$file_name= $path.$uniqueid.".png";
$ecc = 'L';
$pixel_Size = 20;
$frame_Size = 1;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file_name, $ecc, $pixel_Size, $frame_Size);
I tried this approach but it is not working..
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
$uniqueid = uniqid('IT-');
$text = $uniqueid;
$path = '../temp/';
$file_name = $path.$uniqueid.".png";
$ecc = 'L';
$pixel_Size = 20;
$frame_Size = 1;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file_name, $ecc, $pixel_Size, $frame_Size);
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE){
$sql = "INSERT into users (code, name)
values ($text,'".$getData[0]."')";
$result = mysqli_query($conn, $sql);
if(!isset($result)){
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"ad-bulk.php\"
</script>";
} else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"ad-bulk.php\"
</script>";
}
}
fclose($file);
}
}
This is the solution that I came up with. Thank you!
$conn = getdb();
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE){
$uniqueid = uniqid('IT-');
$text = $uniqueid;
$path = '../temp/';
$file_name = $path.$uniqueid.".png";
$ecc = 'L';
$pixel_Size = 20;
$frame_Size = 1;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file_name, $ecc, $pixel_Size, $frame_Size);
echo $getData[0] . "<br>";
echo $text . "<br>";
$sql = "INSERT into users (code, name)
values ('$text','".$getData[0]."')";
echo $sql . "<br>" ;
$result = mysqli_query($conn, $sql);
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"ad-bulk.php\"
</script>";
}
else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"ad-bulk.php\"
</script>";
}
}
fclose($file);
}
}

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

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

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();

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