Import csv file data into database - php

I have to write a code were i need to import the email ids of people with their names which will be on a excel sheet into the database, but the issue which am facing is its displaying me invalid file where as file is in .csv format,please help, am new to this concept,pardon me if i went wrong somewhere.
import.php
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="sel_file" size="20" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$fname = $_FILES['sel_file']['tmp_name'];
echo'Upload file name is'.$fname.' ';
$chk_ext = explode(".",$fname);
if(strtolower(end($chk_ext)) == "csv"){
$filename = $_FILES['sel_file'] ['tmp_name'];
$handle = fopen($filename, "r");
while(($data = fgetcsv($handle, 1000, ",")) !== false)
{
$sql = "INSERT into import_email (vault_no, name, email) values ('".$_SESSION['vault_no']."', '$data[0]', '$data[1]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully imported! ";
}else{
echo "Invalid file!";
}
}
?>

You are using temp name instead of name
$_FILES['sel_file'] ['tmp_name'];
change this to :
$_FILES['sel_file'] ['name'];
example of $_FILE['input_file'] is
[input_file] => Array
(
[name] => MyFile.jpg //<-------- This is the one you should use because it contains the extension (that you are checking for)
[type] => image/jpeg
[tmp_name] => /tmp/php/php6hst32 //<----------- this is the one you used
[error] => UPLOAD_ERR_OK
[size] => 98174
)
So your PHP part should look like this:
<?php
include("connection.php");
if (isset($_POST["submit"])) {
$fname = $_FILES['sel_file']['name']; // Changed only this
echo 'Upload file name is' . $fname . ' ';
$chk_ext = explode(".", $fname);
if (strtolower(end($chk_ext)) == "csv") {
$filename = $_FILES['sel_file'] ['tmp_name'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$sql = "INSERT into import_email (vault_no, name, email) values ('" . $_SESSION['vault_no'] . "', '$data[0]', '$data[1]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully imported! ";
} else {
echo "Invalid file!";
}
}
?>

Related

HTML PHP Form Upload to PHPMyAdmin

I am trying to pass users data through internal html form via Uploading a .csv with 1st row as header, but facing 2 issues:
'hashedpwords.csv' file is generated successfully on same path, but column name of Passwords gets hashed too, even though in code there's a skip first line of file.
data is not being submitted at all to my database table, I couldn't figure out why.
code below:
PHP:
<?php
require_once 'PHP/dbinfo.php';
$dbc = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
$has_title_row = true;
$not_done = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
$filename = basename($_FILES['csvfile']['name']);
if(substr($filename, -3) == 'csv'){
$tmpfile = $_FILES['csvfile']['tmp_name'];
if (($fh = fopen($tmpfile, "r")) !== FALSE) {
$i = 0;
while (($items = fgetcsv($fh, 1000000, ",")) !== FALSE) {
if($has_title_row === true && $i == 0){ // skip the first row if there is a tile row in CSV file
$i++;
continue;
}
set_time_limit(0);
$infile = $filename;
$myfile = "hashedpwords.csv";
$reader = fopen($infile, 'r');
$writer = fopen($myfile, 'w');
$buffer = '';
while ($line = fgetcsv($reader)) {
$line[8] = password_hash($line[8], PASSWORD_DEFAULT);
$buffer .= implode(',', $line) . "\n";
if (strlen($buffer) > 1024) {
fwrite($writer, $buffer);
$buffer = '';
}
}
fwrite($writer, $buffer);
fclose($reader);
fclose($writer);
$sql = "LOAD DATA LOCAL INFILE '".$myfile."'
INTO TABLE usersdata
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
(depid, pid, authid, mainrole, firstname, lastname, username, userinitials, password, mail, phonenumber)";
$result = $dbc->query($sql);
echo "Success";
if (!$result) die("Fatal Error");
if (mysqli_query($dbc, $sql)){
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($dbc);
}
$i++;
}
}
// if there are any not done records found:
if(!empty($not_done)){
echo "<strong>There are some records could not be inserted</strong><br />";
print_r($not_done);
}
}
else{
die('Invalid file format uploaded. Please upload CSV.');
}
}
else{
die('Please upload a CSV file.');
}
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Users Data Upload</title>
</head>
<body>
<form enctype="multipart/form-data" action="userdatauploadfunction.php" method="post" id="add-users">
<table cellpadding="5" cellspacing="0" width="500" border="0">
<tr>
<td class="width"><label for="image">Upload CSV file : </label></td>
<td><input type="file" name="csvfile" id="csvfile" value=""/></td>
<td><input type="submit" name="uploadCSV" value="Upload" /></td>
</tr>
</table>
</form>
</body>
</html>
I fixed the code and it runs properly now. Modified code is below:
PHP:
<?php
$has_title_row = true;
$not_done = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "success";
if(is_uploaded_file($_FILES['csvfile']['tmp_name'])){
//echo "success";
$filename = basename($_FILES['csvfile']['name']);
if(substr($filename, -3) == 'csv'){
//echo "success";
$tmpfile = $_FILES['csvfile']['tmp_name'];
if (($fh = fopen($tmpfile, "r")) !== FALSE) {
//echo "success";
$i = 0;
set_time_limit(0);
$infile = $filename;
$myfile = "hashedpwords.csv";
$reader = fopen($infile, 'r');
$writer = fopen($myfile, 'w');
$buffer = '';
while ($line = fgetcsv($reader)) {
$line[9] = password_hash($line[9], PASSWORD_DEFAULT);
$buffer .= implode(',', $line) . "\n";
if (strlen($buffer) > 1024) {
fwrite($writer, $buffer);
$buffer = '';
}
}
fwrite($writer, $buffer);
fclose($reader);
fclose($writer);
$sql = "LOAD DATA LOCAL INFILE '".$myfile."'
INTO TABLE usersdata
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(uid, depid, pid, authid, mainrole, firstname, lastname, username, userinitials, password, mail, phonenumber)";
require_once 'PHP/dbinfo.php';
$dbc = new mysqli($hn,$user,$pass,$db) or die("Unable to connect");
mysqli_options($dbc, MYSQLI_OPT_LOCAL_INFILE, true);
$result = mysqli_query($dbc, $sql);
//echo "Success";
}
// if there are any not done records found:
if(!empty($not_done)){
echo "<strong>There are some records could not be inserted</strong><br />";
print_r($not_done);
}
}
else{
die('Invalid file format uploaded. Please upload CSV.');
}
}
else{
die('Please upload a CSV file.');
}
}

View uploaded file with $_FILES not functioning

Below are the codes in my system to upload student data in .csv file. For now I have only upload file code and the database will only stored the data inside the .csv file. To view the uploaded file name, I have put code as <?php print_r($_FILES) ?> but the output is as below. Can someone assist me to correct the code?
<?php
include("mainFunc.php");
if(isset($_POST["csv_upload_btn"])) {
if($_FILES['file']['name']){
$filename = explode(".",$_FILES['file']['name']);
if($filename[1] == "csv") {
$failureExists = false;
$handle = fopen($_FILES['file']['tmp_name'], "r");
while($data = fgetcsv($handle,5000,",")){
$item1 = mysqli_real_escape_string($conn, $data[0]);
$item2 = mysqli_real_escape_string($conn, $data[1]);
$item3 = mysqli_real_escape_string($conn, $data[2]);
$item4 = mysqli_real_escape_string($conn, $data[3]);
$item5 = mysqli_real_escape_string($conn, $data[4]);
$item6 = mysqli_real_escape_string($conn, $data[5]);
$item7 = mysqli_real_escape_string($conn, $data[6]);
$item8 = mysqli_real_escape_string($conn, $data[7]);
$item9 = mysqli_real_escape_string($conn, $data[8]);
$item10 = mysqli_real_escape_string($conn, $data[9]);
$query = "INSERT INTO marketing_data(student_matric,student_prg,semester,intake_session,intake_year,student_city,city_lat,city_long,student_state,state_code) VALUES('$item1','$item2','$item3','$item4','$item5','$item6','$item7','$item8','$item9','$item10')";
$run_query = mysqli_query($conn, $query);
if ($run_query == false) {
$failureExists = true;
echo "<script>alert('File " . $_FILES['file']['name'] . " failed to upload')</script>";
}
}
fclose($handle);
if ($failureExists == false) {
echo "<script>alert('File " . $_FILES['file']['name'] . " successfully uploaded')</script>";
}
} else{
echo "<script>alert('File " . $_FILES['file']['name'] . " failed to upload. Please upload .csv file.')</script>";
}
}
}
?>
<form method="POST" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input type="file" name="file" style="width: 350px"; />
<input type="submit" name="csv_upload_btn" value="Upload" />
<div style="text-align: center; font-weight: bold; color: #000000;"><?php print_r($_FILES) ?></div>
</form>
Output
=> Array ( [name] => MARKETING_DATA_2018-2020.csv [type] => application/vnd.ms-excel [tmp_name] => C:\xampp\tmp\phpCADB.tmp [error] => 0 [size] => 97032 ) )

Import data from a csv file to MySQL using PHP

I want to insert data from a CSV file to a MySQL table. For that right now I use the following code, but when I upload the file my browser becomes not-responding. And after few times a pop-up displays that says to restart Firefox or quit Firefox. I just want to know, where is my fault in the given code?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
</head>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="imageup" /><input type="submit" name="submit" value="Upload"/>
</form>
</body>
</html>
<?php
function generateRandomString($length = 10){
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for($i = 0; $i < $length; $i++){
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
if(isset($_POST['submit'])){
$t= generateRandomString();
$path = 'csv/';
$image = $_FILES["imageup"]["name"];
// $tmp = explode(".",$image);
$type = end($tmp);
$file = array("csv");
$csv_file = $path.$image;
if(in_array(strtolower($type), $file)){
if(move_uploaded_file($_FILES["imageup"]["tmp_name"], $path.$image)){
readfile($_FILES['imageup']['tmp_name']);
$open = fopen($_FILES['imageup']['tmp_name'], 'r');
$theData = fgets($open);
$i = 0;
while(!feof($open)){
$csv_data[] = fgets($open, 1024);
$csv_array = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['ID'] = $csv_array[0];
$insert_csv['firstname'] = $csv_array[1];
$insert_csv['lastname'] = $csv_array[2];
$insert_csv['email'] = $csv_array[3];
$isql = "INSERT INTO `myguests`(`id`, `firstname`, `lastname`, `email`) VALUES ('','".$insert_csv['firstname']."','".$insert_csv['lastname']."','".$insert_csv['email']."')";
$run = mysqli_query($con, $isql);
$i++;
}
fclose($open);
echo "File upload successfully";
mysqli_close($con);
}
}
else{
echo "Not valid file formate";
}
}
?>
Please try this I have provide some php code for import data csv format
<body>
<div id="container">
<div id="form">
<?php
$deleterecords = "TRUNCATE TABLE tablename"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded
successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="INSERT into importing(text,number)values('$data[0]','$data[1]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
//view upload form
} else {
print "Upload new csv by browsing to file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
</div>
</div>
</body>
I thing your not making here Database Connection .Check Your database Connetion properly
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
Remove Commnt here // $tmp = explode(".",$image);

Upload CSV into database using php

I am working on a little project of mine and I came to the conclusion that being able to automatically upload a excel sheet to my database would be very, very useful,the problem is that I don´t have an idea of where to start, I have researched a bit and decieded to use a CSV file created from a excel sheet to upload the data into the table of my DB.
Most of the examples I have seem look like a mess with the PHP code into the html instead of dividing the logic in different files like what I have been doing in this last 2 months.
What I have right now is the upload form in html:
<form enctype="multipart/form-data" method="post" id="uploadForm">
<input name="filesfiles" id="upload" type="file" accept=".csv" class="left" />
<input type="submit" value="Cargar" />
</form>
And a small sample of how the CSV file looks in text:
Cedula;Nombre;Apellido1;Apellido2;Correo;IdRol;Estado
1657890;Dominico;Scarlatti;Viera;leetrills#yahoo.com;2;0
5657890;Franz;Listz;Linerman;flizts#hotmail.com;3;0
Or in some other excel versions:
Cedula,Nombre,Primer Apellido,Segundo Apellido,Correo,IDRol,Estado
126548791,Franz ,Ritter ,von Liszt,fliszt#arppegio.com,3,0
174657109,Sofia ,Asgatovna ,Gubaidulina ,gubaidulina#yahoo.com,3,0
The first row is the name of the columns (which should be ignored when adding the info) of the table I want to upload the file into.
The problem is that I don´t know how to link the upload file once the submit button is clicked to a PHP code in my includes that inserts the CSV into the table.
Thanks a lot in advance
EDIT:
JSFiddle of the upload form
EDIT4:
I am a stroke of pure genius and skill Maduka was able to help me solve this behemoth of problem. I can't thank him enough, the following is the code used in hopes that it may serve someone someday and save them the grief of failure.
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING & ~E_STRICT);
mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());
if (isset($_FILES['csvupload'])) {
$errors = array();
$allowed_ext = array('.csv');
$file_name = $_FILES['csvupload']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['csvupload']['size'];
$file_tmp = $_FILES['csvupload']['tmp_name'];
if (in_array($allowed_ext) === false) {
$errors[] = 'La extensión del archivo no es valida.';
}
if ($file_size > 10485760) {
$errors[] = 'El archivo sobrepasa el limite de 10MB';
}
if (empty($errors)) {
$handle = fopen($file_tmp, "r");
while (!feof($handle)) {
$value = (fgetcsv($handle, 0, ','));
if ($i > 0) {
if ($value[0] != '') {
$inserts[] = "('" . mysql_real_escape_string($value[0]) . "','"
. mysql_real_escape_string($value["1"]) . "','"
. mysql_real_escape_string($value["2"]) . "','"
. mysql_real_escape_string($value["3"]) . "','"
. mysql_real_escape_string($value["4"]) . "','"
. mysql_real_escape_string($value["5"]) . "','"
. mysql_real_escape_string($value["6"]) . "')";
}
} elseif ($i == 0) {
$fields = $value;
}
$i++;
}
mysql_query("INSERT INTO `usuarios` (`cedula`,`nombre`,`apellido1`,`apellido2`,`correo`,`idRol`,`estado`) VALUES " . implode(",", $inserts));
fclose($handle);
if ($sq1) {
echo '¡Los usuarios han sido agregados exitosamente!';
}
}
}
?>
Here is the basic code which you need to do your task,
$file = fopen($_FILES['csvUpload']['tmp_name'], "r");
$i = 0;
while (!feof($file)) {
$value = (fgetcsv($file, 0, ';'));
if ($i > 0) {
if ($value[0] != '') {
$inserts[] = "(" . $value[0] . ","
. $value["1"] . ","
. $value["2"] . ","
. $value["3"] . ","
. $value["4"] . ","
. $value["5"] . ","
. $value["6"] . ")";
}
} elseif ($i == 0) {
$fields = $value;
}
$i++;
}
mysql_query("INSERT INTO `MyTable` (`" . $fields[0] . "`,`" . $fields[1] . "`,`" . $fields[2] . "`,`" . $fields[3] . "`,`" . $fields[4] . "`,`" . $fields[5] . "`) VALUES " . implode(",", $inserts));
fclose($file);
You have to implement validation, check file type and size limit. Then insert your data to the table. I have use MySQL bulk insert to handle large amount of data. Hope this helps!
EDIT 1:
Please replace your code with this code and see if it is working correctly.
<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);
mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());
if (isset($_FILES['csvUpload'])) {
$errors = array();
$allowed_ext = array('.csv');
$file_name = $_FILES['csvUpload']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['csvUpload']['size'];
$file_tmp = $_FILES['csvUpload']['tmp_name'];
if (in_array($allowed_ext) === false) {
$errors[] = 'La extensión del archivo no es valida.';
}
if ($file_size > 10485760) {
$errors[] = 'El archivo sobrepasa el limite de 10MB';
}
if (empty($errors)) {
$handle = fopen($file_tmp, "r");
while (($fileop = fgetcsv($handle, ";") && fgetcsv($handle, ",")) !== false) {
$cedula = mysql_real_escape_string($fileop[0]);
$nombre = mysql_real_escape_string($fileop[2]);
$apellido1 = mysql_real_escape_string($fileop[3]);
$apellido2 = mysql_real_escape_string($fileop[4]);
$correo = mysql_real_escape_string($fileop[5]);
$idRol = mysql_real_escape_string($fileop[6]);
$estado = mysql_real_escape_string($fileop[9]);
$sq1 = mysql_query("INSERT INTO `usuarios` (cedula,nombre,apellido1,apellido2,correo,idRol,estado) VALUES ('$cedula','$nombre','$apellido1','$apellido2','$correo','$idRol','$estado')");
}
fclose($handle);
if ($sq1) {
echo '¡Los usuarios han sido agregados exitosamente!';
}
}
}
?>
<form enctype="multipart/form-data" method="post" id="uploadForm">
<input name="csvUpload" id="upload" type="file" accept=".csv" class="left" />
<input type="submit" value="¡Cargar!" />
</form>
Upload form
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<ul><li>
<input name="file" type="file" /><br /></li><li>
<br><input type="submit" name="submit" value="Upload" /></li>
</ul>
</form>
uploader.php
<?php
if (isset($_FILES['file'])) {
$errors = array();
$allowed_ext = array('csv');
$file_name = $_FILES['file']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['file']['size'];
$file_tmp = $_FILES['file']['tmp_name'];
if (in_array($file_ext, $allowed_ext) === false) {
$errors[] ='Extension not allowed';
}
if ($file_size > 10485760) {
$errors[] = 'File size must be under 10mb';
}
if (empty($errors)) {
$handle = fopen($file_tmp,"r");
while(($fileop = fgetcsv($handle,",")) !== false)
{
$companycode = mysql_real_escape_string($fileop[0]);
$pdtcode = mysql_real_escape_string($fileop[2]);
$Item = mysql_real_escape_string($fileop[3]);
$pack = preg_replace('/[^A-Za-z0-9\. -]/', '', $fileop[4]);
$lastmonth = mysql_real_escape_string($fileop[5]);
$ltlmonth = mysql_real_escape_string($fileop[6]);
$op = mysql_real_escape_string($fileop[9]);
$pur = mysql_real_escape_string($fileop[10]);
$sale = mysql_real_escape_string($fileop[12]);
$bal = mysql_real_escape_string($fileop[17]);
$bval = mysql_real_escape_string($fileop[18]);
$sval = mysql_real_escape_string($fileop[19]);
$sq1 = mysql_query("INSERT INTO `sas` (companycode,pdtcode,Item,pack,lastmonth,ltlmonth,op,pur,sale,bal,bval,sval) VALUES ('$companycode','$pdtcode','$Item','$pack','$lastmonth','$ltlmonth','$op','$pur','$sale','$bal','$bval','$sval')");
}
fclose($handle);
if($sq1){
echo 'Stock and Sales successfully updated. Please check the values.<br><br>';
}
}
?>
The above code is simple. I am using for my project.

Import an excel (.csv) into MySQL using PHP code and an HTML form

I know there are other posts similar to this, but everyone recommends just doing it directly in PHPMyAdmin into MySQL (Which works perfectly, but I need to import through an HTML form to PHP to MySQL.
I would like to have an HTML form that collects a file. Then passes that file to a PHP script and I would like to know if it is possible to simply call a PHP function that converts a comma delimeted .csv file into MySQL and adds it to the database.
Or is the only way to parse the file line by line and add each record?
I haven't fully tested this, but I don't see any reason why it wouldn't work.
<?php
if ( isset( $_FILES['userfile'] ) )
{
$csv_file = $_FILES['userfile']['tmp_name'];
if ( ! is_file( $csv_file ) )
exit('File not found.');
$sql = '';
if (($handle = fopen( $csv_file, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql .= "INSERT INTO `table` SET
`column0` = '$data[0]',
`column1` = '$data[1]',
`column2` = '$data[2]';
";
}
fclose($handle);
}
// Insert into database
//exit( $sql );
exit( "Complete!" );
}
?>
<!DOCTYPE html>
<html>
<head>
<title>CSV to MySQL Via PHP</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST">
<input name="userfile" type="file">
<input type="submit" value="Upload">
</form>
</body>
</html>
Of course you would need to validate the data first.
We used this awhile ago, and it works just fine. Just watch your file and directory permissions. csv_upload_mysql_conf.inc is just the DB link. This will parse multiple files at once, and put them in a table called import. Update accordingly.
<?php
/* The conf file */
include_once "csv_upload_mysql_conf.inc";
$php_self = $_SERVER['PHP_SELF'];
$file_open = 0;
$file_exts = array
( 'csv');
#Our Form.....
$form = <<< EOFFORM
<div align='center' style='border: 1px solid #CCC; background-color: #FAFAFA;padding: 10px; color: #006699; width: 620px; font-family: palatino, verdana, arial, sans-serif;' >
<table align=center style='border: 1px solid #CCC; background-color: #FFF;padding: 20px; color: #006699;' cellspacing=1><tbody>
<tr><td>
<form enctype='multipart/form-data' action='$php_self' method='post'><input type='hidden' name='MAX_FILE_SIZE' value='2000000' /><input type='hidden' name='selected' value='yes' /> Selected file: <input name='userfile[]' type='file' id='userfile[]' multiple='' onChange='makeFileList();' /><br /><br /><input type='submit' value='Upload CSV' />
</td></tr></tbody></table></div>
<p>
<strong>Files You Selected:</strong>
</p>
<ul id="fileList"><li>No Files Selected</li></ul>
<script type='text/javascript'>
function makeFileList() {
var input = document.getElementById('userfile[]');
var ul = document.getElementById('fileList');
while (ul.hasChildNodes()) {
ul.removeChild(ul.firstChild);
}
for (var i = 0; i < input.files.length; i++) {
var li = document.createElement('li');
li.innerHTML = input.files[i].name;
ul.appendChild(li);
}
if(!ul.hasChildNodes()) {
var li = document.createElement('li');
li.innerHTML = 'No Files Selected';
ul.appendChild(li);
}
}
</script>
EOFFORM;
#End Form;
if(!isset($_POST['selected'])){
echo "$form";
}
elseif($_POST['selected'] == "yes"){
$uploaddir = 'uploads/';
if(count($_FILES['userfile']['name'])) {
foreach ($_FILES['userfile']['name'] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES['userfile']['tmp_name'][$key];
$name = $_FILES['userfile']['name'][$key];
$f_type = trim(strtolower(end(explode('.', $name))));
if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");
}
$uploadfile = $uploaddir . $name;
if (! file_exists($uploadfile)) {
if (move_uploaded_file($tmp_name, $uploadfile)) {
print "File is valid, and was successfully uploaded. ";
$flag = 1;
chmod($uploadfile, 0777);
} else {
print "File Upload Failed. ";
$flag = 0;
}
$flag = 1;
if ($flag == 1) {
echo "\n parsing Data...";
flush();
if (file_exists($uploadfile)) {
$fp = fopen($uploadfile, 'r') or die (" Can't open the file");
$fileopen = 1;
$length = calculate_length($uploadfile);
}
$replace = "REPLACE";
$field_terminater = ",";
$enclose_option = 1;
$enclosed = '"';
$escaped = '\\\\';
$line_terminator = 1;
$local_option = 1;
$sql_query = 'LOAD DATA';
if ($local_option == "1") {
$sql_query .= ' LOCAL';
}
$sql_query .= ' INFILE \'' . $uploadfile . '\'';
if (!empty($replace)) {
$sql_query .= ' ' . $replace;
}
$sql_query .= ' INTO TABLE ' . "`import`";
if (isset($field_terminater)) {
$sql_query .= ' FIELDS TERMINATED BY \'' . $field_terminater . '\'';
}
if (isset($enclose_option) && strlen($enclose_option) > 0) {
$sql_query .= ' OPTIONALLY';
}
if (strlen($enclosed) > 0) {
$sql_query .= ' ENCLOSED BY \'' . $enclosed . '\'';
}
if (strlen($escaped) > 0) {
$sql_query .= ' ESCAPED BY \'' . $escaped . '\'';
}
if (strlen($line_terminator) > 0){
$sql_query .= ' LINES TERMINATED BY \'' . '\r\n' . '\'';
}
$result = mysql_query ($sql_query);
echo mysql_error() ;
if(mysql_affected_rows() > 1) {
echo " <div align=center><b><font color=#66CC33>The csv data was added.</font></div> ";
}
else {
error_log(mysql_error());
echo " <div align=center><b><font color=#E96B10> Couldn't enter the data to db </font></div>";
}
if ($file_open ==1) {
fclose($fp) or die("Couldn't close the file");
}
}
}
}
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
}
}
function calculate_length($fp) {
$length = 1000;
$array = file($fp);
for($i=0;$i<count($array);$i++)
{
if ($length < strlen($array[$i]))
{
$length = strlen($array[$i]);
}
}
unset($array);
return $length;
}
?>
Everything in your code is fine, only mistake is you are not using mysql_query for inserting the data into table. Mysql query not running in your script. corrected code follows...
<?php
if ( isset( $_FILES['userfile'] ) )
{
$csv_file = $_FILES['userfile']['tmp_name'];
if ( ! is_file( $csv_file ) )
exit('File not found.');
$sql = '';
if (($handle = fopen( $csv_file, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$sql = mysql_query("INSERT INTO `table` SET
`column0` = '$data[0]',
`column1` = '$data[1]',
`column2` = '$data[2]';
");
}
fclose($handle);
}
// Insert into database
//exit( $sql );
exit( "Complete!" );
}
?>
<!DOCTYPE html>
<html>
<head>
<title>CSV to MySQL Via PHP</title>
</head>
<body>
<form enctype="multipart/form-data" method="POST">
<input name="userfile" type="file">
<input type="submit" value="Upload">
</form>
</body>
</html>

Categories