Related
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'm having issues uploading zip files and can't seem to find an answer.
Index.php
<form id="convertFile" action="convert.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input name="upload" type="file" id="inputFile">
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
convert.php:
if(isset($_FILES)){
echo $_FILES['upload']['name'];
}else{
echo json_encode(array('status'=>'error'));
}
When I upload a zip file, I get: Notice: Undefined index: upload in C:\wamp\www\xmlconverter\convert.php on line 3
This is what chrome shows in the post header:
------WebKitFormBoundaryuFNy5dZtFj7olmD5
Content-Disposition: form-data; name="zip_file"; filename="123.zip"
Content-Type: application/x-zip-compressed
------WebKitFormBoundaryuFNy5dZtFj7olmD5--
This works on any other major file format, but can't get it to read the zip file. If I var_dump $_FILES or $_POST they are empty.
What am I missing? Why does all other files work but zip does not.
Thank you
using wamp and php 5.5.12
Where is your zip file type definition?
Anyways, let say this was the html form to upload zip files you'd have the following:
<!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=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>
On the server-side script which handles the post you'd have:
<?php
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "The file you are trying to upload is not a .zip file. Please try again.";
}
$target_path = "/home/var/yoursite/httpdocs/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
//if you also wanted to extract the file after upload
//you can do the following
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "Your .zip file was uploaded and unpacked.";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
?>
I used a script very similar to one posted by #unixmiah without issue on my cPanel based server. Worked great (and has for year now) but ran into issue of error "PHP, undefined index" when using locally with wamp.
Here is the mod that worked for me:
<?php
function rmdir_recursive($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file");
else unlink("$dir/$file");
}
rmdir($dir);
}
if(!empty($_FILES)){
//added above to script and closing } at bottom
if($_FILES["zip_file"]["name"]) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$type = $_FILES["zip_file"]["type"];
$name = explode(".", $filename);
$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$message = "<b>The file you are trying to upload is not a .zip file! Please try again...</b>";
}
$target_path = "somedir/somesubdir/".$filename; // change this to the correct site path
if(move_uploaded_file($source, $target_path)) {
$zip = new ZipArchive();
$x = $zip->open($target_path);
if ($x === true) {
$zip->extractTo("somedir/somesubdir/"); // change this to the correct site path
$zip->close();
unlink($target_path);
}
$message = "<h2>ZIP file was uploaded and content was replaced!</h2>";
} else {
$message = "There was a problem with the upload. Please try again.";
}
}
}
?>
<!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=UTF-8" />
<title>QikSoft ZIP Upper</title>
</head>
<body>
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label><h3>Upload Your ZIP:</h3> <input type="file" name="zip_file" /></label>
<br /><br />
<input type="submit" name="submit" value="START UPLOAD" />
</form>
</body>
</html>
Also note that the echo message has been changed:
<?php if(!empty($message)) echo "<p>$message</p>"; ?>
One thing that does not work is file restriction. Currently allows other types besides ZIP. Anyone with fix, be greatly appreciated.
It's echo $_FILES['upload']['tmp_name'];
Try checking and adjusting the post_max_size value in your php.ini file, this worked for me as the default is 3M, raised the value to 128M and everything was peachy
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.
i have written a code but that is not working. below is a code which enters an image into the database on user input. But my problem is that when i am calling it to print on page, nothing is diaplaying, please help me here.
<?php
$conx=mysqli_connect('localhost','root','sultan','colour');
$sql = "SELECT theme from colors WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
$row=mysqli_fetch_row($sqli);
$theme=$row[0];
if(isset($_POST['submit']))
{
$theme=$_POST['theme'];
$sql = "UPDATE colors SET theme='$theme' WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body{ background-image:url(<?php echo $theme ?>) ;}
</style>
</head>
<body>
<form method="post">
Input your picture<input type="file" name="theme" /><br />
<input type="submit" value="upload" name="submit" />
</form>
</body>
</html>
You need to terminate the statement.
current
<?php echo $theme ?>
new
<?php echo $theme; ?>
<?php
$conx=mysqli_connect('localhost','root','','colour');
$sql = "SELECT theme from colors WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
$row=mysqli_fetch_row($sqli);
$theme=$row[0];
if(isset($_POST['submit']))
{
// new code
$path = '/';
$fileName = $_FILES['theme']["name"];
$fileTmpLoc = $_FILES['theme']["tmp_name"];
$temp = explode(".", $_FILES['theme']["name"]);
$extension = end($temp);
$temp = explode('.', $fileName );
$ext = array_pop($temp );
$name = implode('.', $temp );
$FileNM = $name.time().".".$extension;
$theme = $FileNM.$ext;
move_uploaded_file($_FILES['theme']["tmp_name"], $theme);
$sql = "UPDATE colors SET theme='$theme' WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body{ background-image:url(<?php echo $theme; ?>) ;}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Input your picture<input type="file" name="theme" /><br />
<input type="submit" value="upload" name="submit" />
</form>
</body>
</html>
<?php
$conx=mysqli_connect('localhost','root','','colour');
$sql = "SELECT theme from colors WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
$row=mysqli_fetch_row($sqli);
$theme=$row[0];
if(isset($_POST['submit']))
{
// new code
$error1="";
$error2="";
if ($_FILES["theme"]["type"] !== "image/jpeg"){
echo $error1 = "File is not in JPG!";
}else{
$error1="";
}
if(($_FILES["theme"]["size"] > 1024)){
echo $error2 = "File size not allowed more than 1 MB!";
}else{
$error2="";
}
if($error1 =="" && $error2==""){
$fileName = $_FILES['theme']["name"];
$fileTmpLoc = $_FILES['theme']["tmp_name"];
$temp = explode(".", $_FILES['theme']["name"]);
$extension = end($temp);
$temp = explode('.', $fileName );
$ext = array_pop($temp );
$name = implode('.', $temp );
$FileNM = $name.time().".".$extension;
move_uploaded_file($_FILES['theme']["tmp_name"], "img/".$FileNM);
$sql = "UPDATE colors SET theme='$FileNM' WHERE username='shail' ";
$sqli=mysqli_query($conx,$sql);
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
body{ background-image:url(<?php echo "img/".$FileNM; ?>) ;}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data">
Input your picture<input type="file" name="theme" /><br />
<input type="submit" value="upload" name="submit" />
</form>
</body>
</html>