Uploading Multiple CSV into mysql using PHP - php

I got this code for importing multiple csv file into database but when i tried to upload only one file is being uploaded. I tried many things but just couldn't find a way.
<form name="import" method="post" enctype="multipart/form-data">
<div class="col-lg-6 col-xs-6">
<input type="file" name="file[]" multiple /><br />
</div><!-- ./col -->
<input type="submit" class="form-control"name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
fgetcsv($handle);
while(($filesop = fgetcsv($handle, 10000, ",")) !== false)
{
$ITEM_CODE_MX =$filesop[1];
$addqtyqry = mysqli_query($link,"INSERT INTO salesreceiptlinedetail
(ItemRef_FullName)
VALUES ('".$ITEM_CODE_MX."')");
$c = $c + 1;
}
}
?>

You are allowing multiple files so you need to loop over these multiple file references in the $_FILES array.
Your script was also open to SQL Injection Attack
Even if you are escaping inputs, its not safe!
So I used a prepared and parameterised query prepared parameterized statements
Preparing the statement once and executing it multiple times is one of the ways you can leverage prepared statements to save you execution time.
<form name="import" method="post" enctype="multipart/form-data">
<div class="col-lg-6 col-xs-6">
<input type="file" name="file[]" multiple /><br />
</div><!-- ./col -->
<input type="submit" class="form-control"name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"])) {
//prepare the insert before you start looping
$ins_stmt = $link->prepare('INSERT INTO salesreceiptlinedetail
(ItemRef_FullName) VALUES(?)';
// check the prepare worked and the the query is correctly coded
if (FALSE === $ins_stmt) {
echo 'Error: '.$link->error;
exit;
}
foreach ( $_FILES['file']['tmp_name'] as $file ) {
$handle = fopen($file, "r");
$c = 0;
// read and ignore headers
fgetcsv($handle);
while(($filesop = fgetcsv($handle, 10000, ",")) !== false) {
$ins_stmt->bind_param('s', $filesop[1]);
$ins_stmt->execute();
$c++;
}
}
}
?>

Related

How can i upload csv file to database in php and fix my errors?

I'm trying to upload a csv file into the database,
but only first line gets inserted and it's still insert a blank space for the first field and shift all the other record.
PHP code:
<?php
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$e1 = $filesop[0];
$e2 = $filesop[1];
$e3 = $filesop[2];
$e4 = $filesop[3];
$sql = "INSERT INTO eyfstb(e1,e2,e3,e4) values ('$e1','$e2','$e3','$e4')";
$stmt = mysqli_prepare($db,$sql);
mysqli_stmt_execute($stmt);
$c = $c + 1;
}
if($sql){
echo "sucess";
}
else
{
echo "Sorry! Unable to import the data.";
}
}
?>
File upload Form:
<!DOCTYPE html>
<html>
<body>
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">Only Excel/CSV File Import.</p>
</div>
<button type="submit" class="btn btn-default" name="submit" value="submit">Upload</button>
</form>
</body>
</html>
But it's only first line importing, but i need all data to import.

uploading excel/CSV file data into database

I have to write a code were i need to import the email ids of people with their names which will be on a excel sheet into the database, but the issue which am facing is, it is inserting blank data into the database,please help, am new to this concept,pardon me if i went wrong somewhere.
DB Structure
import.php
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="200" required="">
</div>
<button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>
<?php
if(isset($_POST["Import"]))
{
$con = mysqli_connect("localhost","***","***","***");
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$count = 0;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$count++;
if($count>1){
$query = "INSERT INTO import_email (via, vault_no, name, email, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '$name[0]', '$email[1]', NOW())";
mysqli_query($con, $query);
}
}
fclose($file);
echo 'CSV File has been successfully Imported';
//header('Location: profile_1.php');
}else{
echo 'Invalid File:Please Upload CSV File';
}
}
?>
EXCEL Structure(.csv format)
Thank you.

PHP: undefined offset while importing from csv

I guess you don't have to look at the entire code, but I'll include it anyway.
<?php if (!$_POST) { ?>
<!DOCTYPE html>
<html>
<div class="header">
<img src="images/logo.png" alt="logo" />
</div>
<body background="images/background.png" >
<form action="" method="post" enctype="multipart/form-data">
Choose your file: <br />
<input name="csv" type="file" id="csv" /> <br /> <br />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
<?php
} else {
$connect = new mysqli("localhost", "username", "password", "csvdb");
if ($_FILES['csv']['size'] > 0) {
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($i > 0) {
$import = "INSERT into csvtb(project_id,unit_id,phase,building,level,orientation,apartment_type,size,garden,garden_and_terrace_size,bedrooms,parking,floorplan,sold) values('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]''$data[11]','$data[12]','$data[13],'$data[14])";
$connect->query($import);
}
$i++;
}
fclose($handle);
print "Import done";
}
}
?>
the error is on line 30, undefined offset
$import = "INSERT into csvtb(project_id,unit_id,phase,building,level,orientation,apartment_type,size,garden,garden_and_terrace_size,bedrooms,parking,floorplan,sold) values('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]''$data[11]','$data[12]','$data[13],'$data[14])";
$connect->query($import);
I checked my code using many php online checking tools, they say the code is clean. I guess I know what's the error, i guess it's because I'm not inserting into index 0, that's because I want that to be the id for my database. I'm not sure though, if I were I wouldn't have asked. My PHP skills aren't that good I guess.
It is possible that some lines in your CSV has less data than supplied to the query. I'd recommend handling that in a manner that you can log/debug.
Using your sample code, I have just done some early-exits if data is not found to be valid. You could apply the same kind of logic and print out the lines that do not have total of 15 array element. It appears you are skipping element 0 and choosing 1..14. That's absolutely fine; just check to ensure that all lines are giving you 15 array elements.
<?php
if ($_POST)
{
$connect = new mysqli("localhost", "username", "password", "csvdb");
if ($_FILES['csv']['size'] > 0)
{
//get the csv file
$file = $_FILES['csv']['tmp_name'];
$handle = fopen($file, "r");
$i = 0;
$expected_array_count = 15;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
// skip first line
if ($i == 0) { i++; continue; }
// print offending line and continue to the next line
// if array does not have the expected count
if (count(data) !== $expected_array_count)
{
echo sprintf("Line %d has %d lines; %d expected: %s",
$i+1,
count(data),
$expected_array_count,
implode("~~", $array)
);
i++;
continue;
}
performImport($data);
$i++;
}
fclose($handle);
print "Import done";
}
<?php
}
else
{
<!DOCTYPE html>
<html>
<div class="header">
<img src="images/logo.png" alt="logo" />
</div>
<body background="images/background.png" >
<form action="" method="post" enctype="multipart/form-data">
Choose your file: <br />
<input name="csv" type="file" id="csv" /> <br /> <br />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
}
// function does the importing
function performImport($data)
{
global $connect;
// instead of entering data like this, there are
// better alternatives
$import = "
INSERT into csvtb
(
project_id,unit_id,phase,
building,level,orientation,
apartment_type,size,garden,
garden_and_terrace_size,bedrooms,parking,
floorplan,sold
)
values
(
'$data[1]','$data[2]','$data[3]',
'$data[4]','$data[5]','$data[6]',
'$data[7]','$data[8]','$data[9]',
'$data[10]','$data[11]','$data[12]',
'$data[13]','$data[14]'
)";
// one alterate
// $import = sprintf("insert into ... values (%d, %s, %d...)", $data[1], $data[2] ...)
// another alternate (http://php.net/manual/en/mysqli-stmt.bind-param.php)
// $import = "insert into ... values (?, ?, ...)"
// mysqli_stmt_bind_param($import, 'sss...', $data[1], $data[2]...);
// yet another alternate: use PDO
$connect->query($import);
}
?>

how to save xls file as table in mysql using php

I want to save my excel file as table in database using PHP. Is it possible?
I tried like below. But we need to give table name.
<html>
<head>
<?php
if(isset($_POST["Import"]))
{
include 'database.php';
$filename=$_FILES["file"]["tmp_name"];
$heading=true;
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000)) !== FALSE)
{
$num = count($emapData);
echo $num;
echo $emapData[0];
//check if the heading row
if($heading) {
// unset the heading flag
$heading = false;
// skip the loop
continue;
}
$sql = "INSERT into sheet(name,first_name,last_name) values('$emapData[0]','$emapData[1]','$emapData[2]')";
$row=mysql_query($sql);
}
fclose($file);
echo 'CSV File has been successfully Imported';
}
else
echo 'Invalid File:Please Upload CSV File';
}
?>
</head>
<body>
<form enctype="multipart/form-data" method="post" role="form">
<div class="form-group">
<label for="exampleInputFile">File Upload</label>
<input type="file" name="file" id="file" size="150">
<p class="help-block">
Only Excel/CSV File Import.
</p>
</div>
<button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>
</body>
</html>

PHP Upload and process a CSV file

I have an upload form which takes a csv file. Then I process it with PHP.
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Ladda upp!" class="upload_sub"/>
<br />
<br />
</form>
<?php
if(isset($_POST['submit'])) {
if($_FILES["csv"]["error"] > 0) {
echo 'Ett fel inträffade vid uppladdning av filen. Var god försök igen.';
} else {
$tmp = $_FILES['csv']['tmp_name'];
$import = new Importer();
$import->importTariff($tmp);
}
}
?>
lib.php class Importer ( I only submit the relevant function )
public function importTariff($tmp) {
if(($handle = fopen($tmp, 'r')) !== FALSE) {
while(($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
echo 'foo';
}
}
}
For testing purposes I would like to print 'foo' for each line in the csv. However I get no errors or anything like it so any ideas?
print_r($_FILES);
Check out your NAME from file-input:
<input type="file" name="file" id="file" />
Rename it to name="csv" or change $_FILES["csv"] to $_FILES["file"]
The issue was not PHP related. I've looked into the table design and I noticed that the id column was unsigned and not checked for incredement.

Categories