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.');
}
}
Related
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!";
}
}
?>
I am trying to write a code on PHP that will allow me to upload some specific columns from a CSV file to MySql table. I'm very new on PHP. Tried to watch some of tutorials, but they were not much helpful as they are only showing the examples on very little CSV files such as 2 rows and 2 columns... I am talking about approx 100 cols and hundreds of rows. I only need the information from some specific columns to add my table. Here's my code so far.. It gives Undefined offset error. I am open to new ideas.
$connection = mysqli_connect('localhost', 'root', 'MyPass', 'database') or die('connection failed');
if(isset($_POST['upload'])){
$fname = $_FILES['sel_file']['name'];
echo 'upload file name: '.$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, 10, ",")) !== FALSE)
{
$sql = "INSERT into turbolister(site,format,currency) values('$data[0]','$data[1]','$data[2]')";
mysqli_query($connection, $sql) or die(mysqli_error($connection));
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
} `
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br>
<input class="btn btn-primary" type="submit" name="upload" value='upload'>
</form>
For such a project I would recommend you another way of doing this.
For me there are some open questions:
Is it correct, that one line in csv is one line in database?
Is there a header-line in csv containing the column-names so that the order of the columns can change?
I've overworked your script a little bit - what you need to do is to adjust the behavior to your needs and also change the separation item for header-columns and normal-lines.
<?php
// Just for development purpose
error_reporting(E_ALL);
ini_set('display_errors', 1);
try {
// Try to connect to mysql-server with pdo instated of using mysqli
$dbCon = new PDO('mysql:dbname=testdb;host=127.0.0.1', 'root', 'MyPass');
} catch (PDOException $e) {
// Catching error && stoping script
die('<strong>Error:</strong> Connection failed with error "' . $e->getMessage() . '"');
}
if(isset($_POST['upload'])) {
$filename = $_FILES['sel_file']['name'];
// Show filename of uploaded file
echo 'Uploaded file: ' . $filename . '<br>';
// Check file-extension for csv
// #ToDo: Determinate which mime-type your csv-files generally have and check for mime-type additionally or instated
if (pathinfo($filename, PATHINFO_EXTENSION) == 'csv') {
// Get file-content
$fileContent = file_get_contents($_FILES['sel_file']['tmp_name']);
// Split file into lines
$rows = explode("\n", $fileContent);
// Check for data
if (empty($rows) || count($rows) < 2) {
// Shwo error-messages && stopping script
die('<strong>Error:</strong> CSV-File does not contain data!');
}
// Get columns of header-row
$header = explode('|', $rows[0]);
// Set query variables
$query = 'INSERT INTO test (';
$values = '(';
// Build query based on header-columns
for($a = 0; $a < count($header); ++$a) {
// Add column
$query .= $header[$a] . ', ';
$values .= ':column' . $a . ', ';
}
// Finish query
$query = substr($query, 0, -2) . ') VALUES ' . substr($values, 0, -2) . ')';
// Loop through rows, starting after header-row
for ($b = 1; $b < count($rows); ++$b) {
// Split row
$row = explode(',', $rows[$b]);
// Check that row has the same amount of columns like header
if (count($header) != count($row)) {
// Show message
echo '<strong>Warning:</strong> Skipped line #' . $b . ' because of missing columns!';
// Skip line
continue;
}
// Create statement
$statement = $dbCon->prepare($query);
// Loop through columns
for ($c = 0; $c < count($row); ++$c) {
// Bind values from column to statement
$statement->bindValue(':column' . $c, $row[$c]);
}
// Execute statement
$result = $statement->execute();
// Check for error
if ($result === false) {
// Show info
echo '<strong>Warning:</strong>: DB-Driver returned error on inserting line #' . $b;
}
}
// #ToDo: Get numbers of row before import, check number of rows after import against number of rows in file
// Show success message
echo '<span style="color: green; font-weight: bold;">Import successfully!</span>';
} else {
die('<strong>Error:</strong> The file-extension of uploaded file is wrong! Needs to be ".csv".');
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
Import File: <input class="btn btn-primary" type="file" name='sel_file' size='20'> <br>
<input class="btn btn-primary" type="submit" name="upload" value='upload'>
</form>
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);
I'm importing my csv fine now except one thing, how do i get the import to ignore the data in the first row? Employees will be uploading the same format which has the column names in that first row.
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 tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
just set a variable $i = 0 Then only insert when $i = 1 or more
if (isset($_POST['submit'])) {
$i=0; //so we can skip first row
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) {
if($i>0) {
$import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
$i++;
}
fclose($handle);
print "Import done";
}
You can simply use MySQL's LOAD DATA INFILE command, which will be considerably faster than parsing the CSV into PHP, constructing an INSERT statement for every record, submitting it as a string to MySQL and having MySQL parse said string for SQL (at risk of SQL injection):
LOAD DATA INFILE ? INTO TABLE tictoc
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = ?, taskname = ?
Using PDO:
$dbh = new PDO('mysql:dbname='.$dbname, $username, $password);
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
$qry = $dbh->prepare('
LOAD DATA INFILE :filepath INTO TABLE tictoc
FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'"\'
IGNORE 1 LINES
(tasktime, sessiontime, sessionstart, sessionend, sessionnotes)
SET employee = :employee, taskname = :taskname
');
$qry->execute(array(
':filepath' => $_FILES['filename']['tmp_name'],
':employee' => $userinfo['first_name'],
':taskname' => $userinfo['last_name']
));
}
maybe you can use this way if you like:
$i=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$i++;
if($i==1) continue;
$import="INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('".$userinfo['first_name']." ".$userinfo['last_name']."','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
No variable needed. It is much simpler than this. Here is a solution that requires the least amount of foreign code, and works just fine. Try putting:
$headers = fgetcsv($handle, 1000, ",");
Before your while() loop that grabs the CSV data. That grabs the headers, but leaves them out from being inserted into the database. Once the while loop begins, the first line has already been returned thus leaving them out of the mysql insert. On top of this it appears the headers were needed and so this solves that as well.
So in the end,
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");
//Grab the headers before doing insertion
$headers = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
You can try this:
array_shift($data);
I have implement this code and it is tested code. I think it is very use full
You have follow some rule:-
1.your csv file according to database table name (ex: db table name is users then csv should be users.csv)
2.Your csv file's first row should be db table fields name (ex: Id, name etc) after the start your data entry
3.you can download data source class from :- http://code.google.com/p/php-csv-parser/ because i have require below the code: require_once 'CSV/DataSource.php';
<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";
$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());
require_once 'CSV/DataSource.php';
$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;
$dbtable = $ext[0];
import_csv($dbtable, $path);
function import_csv($dbtable, $csv_file_name_with_path)
{
$csv = new File_CSV_DataSource;
$csv->load($csv_file_name_with_path);
$csvData = $csv->connect();
$res='';
foreach($csvData as $key)
{
$myKey ='';
$myVal='';
foreach($key as $k=>$v)
{
$myKey .=$k.',';
$myVal .="'".$v."',";
}
$myKey = substr($myKey, 0, -1);
$myVal = substr($myVal, 0, -1);
$query="insert into ".$dbtable." ($myKey)values($myVal)";
$res= mysql_query($query);
}
if($res ==1)
{
echo "record successfully Import.";
}else{
echo "record not successfully Import.";
}
}
Declare one variable before while loop
$row=1;
then in while loop put this condition
if($row==1){
$row++;
continue;
}
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");
fgetcsv($handle); //skip the reading of the first line from the csv file
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT into tictoc(employee,taskname,tasktime,sessiontime,sessionstart,sessionend,sessionnotes) values('" . $userinfo['first_name'] . " " . $userinfo['last_name'] . "','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}
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>