Import csv into database with same matching header In php - php

I have a table in database with fields (Id,Name,Email,Employee Code,Joining Date,Address) and i have a csv file which containing same fields. I have to import csv file into database with same header. If header is different then it should not import into database and throw an error. I have to check while uploading csv into database, if any value(email or Employee code) is already in the database then it should ignore the field and throw an error.
Please help .
if(isset($_POST["Import"]))
{
$host="localhost"; // Host name.
$db_user="root";
$db_password="password";
$db='testcsv'; // Database name.
$conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
$fieldinfo=array();
echo $filename=$_FILES["file"]["tmp_name"];
$query="SELECT * FROM csv";
$output=mysql_query($conn,$query);
while ($fieldinfo=mysqli_fetch_field($output))
{
$columns=$fieldinfo;
}
echo $query;
echo "<br/>";
print_r($output);
echo "<br/>";
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
$header = fgetcsv($file);
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$record = array_combine($header, $emapData);
echo "<br>";
echo $record;
echo "<br>";
$sql = "INSERT into csv(Name,Email,EmployeeCode,JoiningDate,Address) values('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]')";
mysql_query($sql);
}
fclose($file);
echo "CSV File has been successfully Imported";
}
else
echo "Invalid File:Please Upload CSV File";
}
?>
<!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 CSV/Excel file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<table border="1" width="40%" align="center">
<tr >
<td colspan="2" align="center"><strong>Import CSV/Excel file</strong></td>
</tr>
<tr>
<td align="center">CSV/Excel File:</td><td><input type="file" name="file" id="file"></td></tr>
<tr >
<td colspan="2" align="center"><input type="submit" name="Import" value="Import"></td>
</tr>
</table>
</form>
</body>
</html>

Related

CSV Upload Issue

I am uploading the csv file in php mysql with the following code:
en<?php
session_start();
if(!isset($_SESSION["UID"]))
{
header("Location: index.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= 'crm_6feb'; // Database Name.
$conn=mysqli_connect($host,$db_user,$db_password) or die("unable to connect to database");
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";
$count = 0;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$count++;
if($count>1){
echo $sql = "insert into enquiry(en_name,en_mobile,en_landline,en_email,en_address,salesid,date_recieved,duplicate,date_add,ip) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]',$emapData[5],$emapData[6],'$emapData[7]',$emapData[8],'$emapData[9]')";
$RES = mysqli_query($conn, $sql) or die("error in insert");
}
}
fclose($file);
echo 'CSV File has been successfully Imported';
header('Location: importleads.php');
}
else
echo 'Invalid File:Please Upload CSV File';
}?>
<!DOCTYPE html>
<html>
<head>
<title>Add Order Status</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<?php include("includes/header.php");?>
<div class="box">
<h2>Add Order Status</h2>
<div class="display">
<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>
</div></div></body></html>
Now, after I click upload button, I get the following message as an error :
C:\wamp\tmp\phpBEC.tmp error in insert
The excel contents is as follows:
Name| Mobile| Alternate Number|Email| Address| Sales id| Date Rec| Dupli|Date Add| Ip
Kindly suggest where i am doing things wrong.
Awaiting revert for your help.

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>";
?>

Convert csv file into mysql databse using php

I have a csv file like the one below and I want to convert it to a msql database. In my csv file there are so many lines I want to find a quick way to copy everything. Someone tell me would know what to look for or kindly post the code used? Thank you!
This is the example of csv file that I need to copy in db
Numero SAT,Stato SAT,Tipo servizio,Data attivazione,Imei guasto,Imei consegnato,Marca terminale,Modello terminale,Famiglia guasto,Descrizione guasto
SAT100000002572,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002573,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002574,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002575,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002576,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
I tried to do with this code, someone can fix it?
<?php
$message = null;
$allowed_extensions = array('csv');
$upload_path = 'C:\xampp\htdocs\exercise-files\start';
if (!empty($_FILES['file'])) {
if ($_FILES['file']['error'] == 0) {
// check extension
$file = explode(".", $_FILES['file']['name']);
$extension = array_pop($file);
if (in_array($extension, $allowed_extensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) {
if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) {
$keys = array();
$out = array();
$insert = array();
$line = 1;
while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) {
foreach($row as $key => $value) {
if ($line === 1) {
$keys[$key] = $value;
} else {
$out[$line][$key] = $value;
}
}
$line++;
}
fclose($handle);
if (!empty($keys) && !empty($out)) {
$db = new PDO('mysql:host=localhost;dbname=satingestione', 'root', '');
$db->exec("SET CHARACTER SET utf8");
foreach($out as $key => $value) {
$sql = "INSERT INTO `sgestite` (`";
$sql .= implode("`, `", $keys);
$sql .= "`) VALUES (";
$sql .= implode(", ", array_fill(0, count($keys), "?"));
$sql .= ")";
echo $sql;
echo "------------------------------------------------\n";
//$statement = $db->prepare($sql);
//$statement->execute($value);
}
$message = '<span class="green">File has been uploaded successfully</span>';
}
}
}
} else {
$message = '<span class="red">Only .csv file format is allowed</span>';
}
} else {
$message = '<span class="red">There was a problem with your file</span>';
}
}
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Upload CSV to MySQL</title>
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<section id="wrapper">
<form action="" method="post" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" border="0" class="table">
<tr>
<th><label for="file">Select file</label> <?php echo $message; ?></th>
</tr>
<tr>
<td><input type="file" name="file" id="file" size="30" /></td>
</tr>
<tr>
<td><input type="submit" id="btn" class="fl_l" value="Submit" /></td>
</tr>
</table>
</form>
</section>
</body>
</html>
This is a working example please change your code accordingly and you are Done :)
<?php
//connect to the database
$connect = mysql_connect("localhost","username","password");
mysql_select_db("mydatabase",$connect); //select the table
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!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 ?>
I'm explaining a simple way to do this.
<?php
$input = file_get_contents('./path/input.csv');
//each lines will be an array element
$lines_array = explode("\n", $input);
foreach ($lines as $key => $value) {
//each lines again splitted to objects by comma
$each_line = explode(",", $value);
//now you have each object in each line as array
/* for example
$eachline[0] will be equal to 'Numero SAT'
$eachline[1] will be equal to 'Stato SAT'
$eachline[2] will be equal to 'Tipo servizio'
$eachline[3] will be equal to 'Data attivazione'
and so on */
// Now do the process as you wish.
}
?>
And I think for MySQL, you have the provision to upload csv file as such to create a table.

import .csv in mysql script php

i got a PHP script to import a file into my mysql database.
but when i try to use it i get this error:
File not found. Make sure you specified the correct path
but i did not even select a file this is my script:
<?php
include ('db_connect.php');
//connect to the database
//
if ($_FILES[csv][size] > 0) {
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
)
");
}
} while ($data = fgetcsv($handle,10000,",","'"));
//
//redirect
header('Location: import.php?success=1'); die;
}
?>
<!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>
any1 who can hlp me with this problem?
Re comment about do/while loop: no, I mean like this
$handle = fopen($file,"r");
if ($handle !== FALSE) {
while (!feof($handle)) {
$data = fgetcsv($handle,10000,",","'");
if ($data[0]) {
mysql_query("INSERT INTO test (nummer, branche) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."'
)
");
}
}
fclose($handle);
}

how to upload image code and save path into mysql db

how to write code to upload image and save path into mysql db?
i have tried but none are working.
One way is to upload image and store it in a folder on server, and save name to mysql database. Here's an example ::
First we'll create a form to upload ::
//file.html
Upload your file to the database...
<form action="upload.php" method="post" enctype="multipart/form-data" name="uploadform">
<input type="hidden" name="MAX_FILE_SIZE" value="350000">
<input name="picture" type="file" id="picture" size="50">
<input name="upload" type="submit" id="upload" value="Upload Picture!">
</form>
Then we create upload.php
<!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> Upload Image </title>
<?php
// if something was posted, start the process...
if(isset($_POST['upload']))
{
// define the posted file into variables
$name = $_FILES['picture']['name'];
$tmp_name = $_FILES['picture']['tmp_name'];
$type = $_FILES['picture']['type'];
$size = $_FILES['picture']['size'];
// if your server has magic quotes turned off, add slashes manually
if(!get_magic_quotes_gpc()){
$name = addslashes($name);
}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, $size);
$content = addslashes($content);
fclose($extract);
// connect to the database
include "connect.php";
// the query that will add this to the database
$addfile = "INSERT INTO files (name, size, type, content ) VALUES ('$name', '$size', '$type', '$content')";
mysql_query($addfile) or die(mysql_error());
if(!empty($_FILES))
{
$target = "upload/";
$target = $target . basename( $_FILES['picture']['name']) ;
$ok=1;
$picture_size = $_FILES['picture']['size'];
$picture_type=$_FILES['picture']['type'];
//This is our size condition
if ($picture_size > 5000000)
{
echo "Your file is too large.<br>";
$ok=0;
}
//This is our limit file type condition
if ($picture_type =="text/php")
{
echo "No PHP files<br>";
$ok=0;
}
//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo "Sorry your file was not uploaded";
}
//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['picture']['name']). " has been uploaded <br/>";
}
else
{
echo "Sorry, there was a problem uploading your file.";
}
}
}
mysql_close();
echo "Successfully uploaded your picture!";
}else{die("No uploaded file present");
}
?>
</head>
<body>
<div align="center">
<img src="upload/<?php echo $name; ?>"
<br />
upload more images
</div>
</body>
</html>
//getpicture.php
**//Finally the connect.php**

Categories