Convert csv file into mysql databse using php - 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.

Related

Problems to compare two strings in PHP

I created a code in PHP. This code basically take to files .csv and comparer the strings inside in this files.
Here is my code:
index:
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Triangulação</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv1" value="" />
<br>
<input type="file" name="csv2" value="" />
<br>
<input type="submit" name="submit" value="Save" />
</form>
</body>
</html>
Upload:
<?php
$csv = array();
// check there are no errors
if($_FILES['csv1']['error'] == 0 && $_FILES['csv2']['error'] == 0){
$name1 = $_FILES['csv1']['name'];
$name2 = $_FILES['csv2']['name'];
$ext1 = strtolower(explode('.', $_FILES['csv1']['name'])[1]);
$ext2 = strtolower(explode('.', $_FILES['csv2']['name'])[1]);
$type1 = $_FILES['csv1']['type'];
$type2 = $_FILES['csv2']['type'];
$tmpName1 = $_FILES['csv1']['tmp_name'];
$tmpName2 = $_FILES['csv2']['tmp_name'];
// check the file is a csv
if($ext1 == 'csv' && $ext2 == 'csv'){
if(($handle1 = fopen($tmpName1, 'r')) != FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 0;
while(($data1 = fgetcsv($handle1, 1024, ',')) != FALSE) {
// number of fields in the csv
if(($handle2 = fopen($tmpName2, 'r')) != FALSE){
set_time_limit(0);
$dna1 = $data1[1];
while(($data2 = fgetcsv($handle2, 1024, ',')) != FALSE) {
$dna2 = $data2[1];
if(strcmp($dna1, $dna2) == 0){
printf("<p> %s </p>", $dna1);
}
}
fclose($handle2);
}
}
fclose($handle1);
}
}
}
?>
Something is wrong in this part: if(strcmp($dna1, $dna2) == 0).
I do not know why this code has a error:
Here is the files csv that i used:
file1: https://github.com/rrodrigofranco/fornoPID/blob/main/B802828_Family_Finder_Matches_2021-10-02.csv
file2: https://github.com/rrodrigofranco/fornoPID/blob/main/B802890_Family_Finder_Matches_2021-10-02.csv
Someone can help me?

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

Import csv into database with same matching header In 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>

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

failed to open stream: No such file or directory PHP [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have an upload form in a php page , that puts a csv file into a database.
I'm getting an error upon submission of my csv file:
Warning: move_uploaded_file(/public_html/csv/test/books.csv) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/blakeloi/public_html/csv/index.php on line 19
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpZw2e2X' to '/public_html/csv/test/books.csv' in /home/blakeloi/public_html/csv/index.php on line 19
This is the line that is wrong:
$upload_path = '/Users/blakeloizides/Desktop';
In:
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name']))
I have tried renaming my file path many times now, and nothing seems to work. The most obvious answer would be that my file directory path is wrong , but I put the folder into my browser and got the correct path. I even tried to use a folder on my server /public_html/test, but this did not work.
<?php
$message = null;
$allowed_extensions = array('csv');
$upload_path = '/Users/blakeloizides/Desktop';
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=blakeloi_import-csv', 'blakeloi_root', 'password');
$db->exec("SET CHARACTER SET utf8");
foreach($out as $key => $value) {
$sql = "INSERT INTO `books` (`";
$sql .= implode("`, `", $keys);
$sql .= "`) VALUES (";
$sql .= implode(", ", array_fill(0, count($keys), "?"));
$sql .= ")";
$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>
My index.php file is sitting in public_html/csv or http://www.blakeloizides.co.za/csv
and I want to upload the file to public_html/csv/test or http://www.blakeloizides.co.za/csv/test
My permissions are 755 for both folders.
I had to change my file path to /home/blakeloi/public_html/csv/test . That was my error I was using /public_html/csv/test

Categories