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.
what is the problem in the code below ? instead that the data is put into the row firstname and lastname the data is join into row firstname . i have sample screenshot in excel , and inserted data in the database , help would be appreciated. thanks
data in the databaseexcel file format
<form enctype="multipart/form-data" method="post" action="import.php" 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"> from excel save us .csv<p>
</div>
<button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
</form>
<?php
if(isset($_POST["Import"]))
{
//First we need to make a connection with the database
$host='localhost'; // Host Name.
$db_user= 'root'; //User Name
$db_password= '';
$db= 'testdatabase'; // Database Name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
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) {
$sql = "INSERT into person(firstname , lastname) values ('$emapData[0]','$emapData[1]')";
mysql_query($sql);
}
}
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: index.php');
echo "Data was successfully added!";
}
else
echo 'Invalid File:Please Upload CSV File';
}
?>
My guess is that your problem is there:
while (($emapData = fgetcsv($file, 10000, ";")) !== FALSE)
The problem with Excel creating a CSV file is the dependency with system configuration. I work a lot with french configuration wich is default setuped with ; as delimiter.
The best would be to ask the delemiter instead of hardcoding it in the php script, that's how I do it usually, or you could use the header the find what is between firstname and lastname, that would be your delimiter.
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>";
?>
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);
}
?>
I want to upload CSV file to mysql database but i got error can any one help me please i am new in php
Warning: fopen() [function.fopen]: Filename cannot be empty
Here Is code please help me
<?php
$connect = mysql_connect("localhost","root","");
mysql_select_db("csv",$connect);
?>
<?php
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h3>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." ."</h3>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$firstRow = true;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($firstRow) { $firstRow = false; }
else {
$import="INSERT into product_details(pname,price,total) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
}
fclose($handle);
print "Import done";
}else { ?>
<h3>Upload new csv by Browsing to file and Clicking on Upload</h3><br />
<form enctype="multipart/form-data" action='' method='post'>
<input type="file" name="filename" onchange="checkfile(this);" ><br /><br />
<input class="btn btn btn-primary" type="submit" name="submit" value="Upload">
</form>
In advance thanks