Import data from a csv file to MySQL using PHP - 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);

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

CSV file upload with data validation

I'm trying to upload a *.CSV file to the database using PhP.
I can't really make the data validation work with the file upload.
The script should see if the data from certain cells is valid by searching in the db's tables.
The file should not be uploaded if there are errors!
Here's the code!
<form name="import" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection2.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$err = 0;
if ($_FILES["file"]["type"]=='application/vnd.ms-excel')
{
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$query = mysqli_query("SELECT * FROM modele WHERE `model` = '".$model."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Model error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM judete WHERE `nume` = '".$judet."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Judet error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM beneficiari WHERE `nume` = '".$beneficiar."'");
if (!empty($query)) {
$err ++;
$msg=$msg." Beneficiar error on row $c <br>";
}
// if (strlen($tid)!==8){
// $err ++;
// $msg=$msg."TID length error at row $c <br>";
// }
$c ++;
}
if ($err!==0){
echo $msg; echo "ERROR COUNT= ".$err;
break;
}
$c=0;
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$qry=mysql_query("SELECT id FROM beneficiari WHERE `nume` = '".$beneficiar."'");
while ($row = mysql_fetch_assoc($qry)){
$id_client=$row['id'];
echo "Beneficiar=".$row['id'];
}
$qry_id_model=mysql_query("SELECT id FROM modele WHERE `model` = '".$model."'");
while ($row = mysql_fetch_assoc($qry_id_model)){
$id_model=$row['id'];
echo "Model=".$row['id'];
}
echo "MODEL2:".$id_model;
$adresa1 = $adresa.", ".$localitate;
if ($c!==0){
$sql = mysql_query("INSERT INTO equipments
(id_client, model, tid, beneficiar, adresa, agentie, judet)
VALUES
('$id_client','$id_model','$tid','$beneficiar','$adresa1','$locatie','$judet')");
}
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recordes <br>";
}else{
echo "Sorry! There is some problem.<br>";
}
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
}
else echo "NOT CSV!";
}
?>
What's wrong here?
When i try to run it the data is not uploaded and no errors are shown, I left errors in the file to test it. Also i uploaded a clean file and also the file is not uploaded. If i break the code in 2 and make 2 separate codes, one to verify and one to upload, the upload works, but i need the verification and the upload to be in the same code. also tried mysql_query in stead of mysqli_query.
The procedural style of mysqli_query takes 2 arguments - the connection and the query. You're only passing the query.
You can read the official documentation for the mysqli_query() method here:
http://php.net/manual/en/mysqli.query.php
A suggestion as to how to approach this would be something like:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if(!$link)
{
echo("Unable to connect");
} else {
if($ret = mysqli_query($link, "SELECT id FROM modele WHERE `model` = '".mysqli_real_escape_string($link, $model)."'"))
{
$data = mysqli_fetch_assoc($ret);
echo($data["id"]);
}
mysqli_close($link);
}
Important: Note my use of mysqli_real_escape_string in the example above - your current code leaves you vulnerable to SQL injection attacks.
first of all you should upload this file on a temporary folder and save the file name. Then use getCSV php function to read properly the file.
Finally you can check if it's all OK, insert on database, and, if not, echo an error message and delete the file (remember we saved the name and we know the static route of the temporary folder).
Hope it helps!

Import csv file data into database

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

get specific row from csv file when importing into phpmysqladmin

I'm new in here, I'm trying to get a Specific rows for a calendar csv file and import to phpmysql database but could not actually get it, hoping someone can hep me
this is my csv file
this is my database look like, i want to get row 4,6,8...so on from csv file and import to table:calendar, column:day and get row 3,5,7...to the same table but column:date
And this is my code
<?php
include "dbFunctions.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE calendar"; //empty the table of its current records
mysqli_query($link, $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
//exclude the first row title
$row = 1;
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($i=0; $i<=38; $i++){
if($firstRow) { $firstRow = false; }
else {
$import="INSERT into class(day, date)
values('$data[0]','$data[1]')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
echo $data[$i] . "<br />\n";
}}
fclose($handle);
}
//view upload form
}else {
print "Upload csv file and clicking on Upload<br />\n";
print "<form enctype='multipart/form-data' action='uploadCalendar.php' method='post'>";
print "csv File to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
Since the patterns are odd and even rows.
$row = 0;
$i = 0;
$container = array();
if(($handle = fopen($_FILES['filename']['tmp_name'], "r")) !== FALSE){
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row > 2) {
if ($row % 2 == 0) {
$i = $i - 6;
$v = 'day';
} else {
$v = 'date';
}
foreach ($data as $column) {
$container[$i][$v] = $column;
$i++;
}
}
$row++;
}
fclose($handle);
}
foreach ($container as $value) {
$import="INSERT into class(day, date)
values('".$value['day']."','".$value['date']."')";
mysqli_query($link, $import) or die(mysqli_error($link));
}
The $container should contain the date paired to the day. Like,
$container = [['day' => 'W1D1', 'date' => '19-Oct'], ['day' => 'W1D2', 'date' => '20-Oct']];
And you can use loop to insert into database.

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