PHP: undefined offset while importing from csv - php

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);
}
?>

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 Multiple CSV into mysql using 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++;
}
}
}
?>

undefined offset 1 when trying to import csv file in database

i am trying import csv file in database but it showing undefined offset 1 and it storing values in db as
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿRoot Entryÿÿÿÿÿÿÿÿ
i don't know why.i was trying to fix that error from past 5 hours but i coudn't
here is my code
<body>
<form name="import" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$filesop = array();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];
$sql = mysql_query("INSERT INTO mdl_user (username, email) VALUES
('$name','$email')");
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted
". $c ." recoreds";
}else{
echo "Sorry! There is some problem.";
}
}
?>
</body>
it showing undefined offset 1 error in this line
$email = $filesop[1];
can anyone help me
thanks in advance..

how to import csv sheet to mysql database using php and html

I want to import csv sheet to MYSQL database using HTML form,
now i can import successfully but the problem is, i have to give inputfile path in script only, so that user can upload the csv file and as soon as the file is uploaded, call the function and pass the ‘path of file’ as the parameter.
Below i tried this code,
<?php
$delimiter = ',';
$db = new mysqli('localhost', 'root', '', 'ProcessTrackingSystem');
if (($handle = fopen("/var/www/html/new/database_template.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
foreach($data as $i => $content) {
$data[$i] = $db->real_escape_string($content);
}
$db->query("INSERT INTO ProcessTrackingSystem.ProcessDetails VALUES('" . implode("','", $data) . "');");
}
fclose($handle);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<?php
if (!empty($_GET[success])) { echo "<b>Your file has been imported. </b><br><br>"; } //generic success notice
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
Choose your file: <br />
<input name="csv" type="file" id="csv" />
<input type="submit" name="Submit" value="Submit" />
</form>
</body>
</html>
this script is taking input but we have to specify the path in code, help me to take user input.
thanks in advance.
I got desired output by below code,
<?php if (!$_POST) { ?>
<html>
<body>
<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", "root", "", "ProcessTrackingSystem");
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 ProcessTrackingSystem.ProcessDetails VALUES('" . implode("','", $data) . "');");
$connect->query($import);
}
$i++;
}
fclose($handle);
print "Import done";
}
}
?>
this code is providing user to upload csv file from web form.
Assuming you have have a CSV file with following format and first column corresponding your field name:
column name1 column name2 column name3
Value1 Value2 Value3
Value4 Value5 Value6
<?
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r"); // Get File's data
$columnArray=array();//stores the column
$dataArray=array();//store all rows
$records=""//store the all records in string format
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { //Get Excel sheet data row by row
if($f==0){ //Store first row as column headings
foreach ($data as $k=>$v){
$columnArray[$k]=strtolower(str_replace(" ","_",$v));
}
}else{
// Store insert string for payment record
foreach ($data as $k=>$v){
$dataArray[$f][$k]=$v;
$records.="'".$v."',";
}
if($records!=""){
$records.="'0',now()),(";
}
}
$f++;
}
fclose($handle);//close file
if($records!=""){ // Insert payment record string
$records=substr($records, 0, -3);
$colStr=implode($columnArray,",");
$insertQuery="INSERT INTO table_name (".$colStr.",checked,dateval) VALUES (".$records.")";
$this->EbsPaymentDetail->query($insertQuery);
}
$n=0;
//Display table containing records imported
$dataTable.= "<h2><strong>Following records has been successfully Imported !!</strong></h2><table width='100%'><tr><td><strong>S No.</strong></td>";
foreach ($columnArray as $k=>$v){
$dataTable.= "<td><strong>".ucwords(str_replace("_"," ",$v))."</strong></td>";
}
$dataTable.= "</tr>";
foreach ($dataArray as $k=>$v){
$dataTable.= "<tr>";
$dataTable.= "<td>".++$n."</td>";
for($j=0;$j<count($v);$j++){
$dataTable.= "<td>".$v[$j]."</td>";
}
$dataTable.= "</tr>";
}
$dataTable.= "</table>";
?>

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