Following is my script to upload the table employee with a csv file. The file is uploading and upldating the employee table perfectly. BUT the problem is i specified a row with headings in the csv file. That heading row is also getting updated in the table. I want only those datas to get uploaded except the heading row in the csv file, any help or ideas?.
<?php
require_once '../config.php';
if(isset($_POST['upload']))
{
$fname = $_FILES['sel_file']['name'];
$chk_file = explode(".",$fname);
if(strtolower($chk_file[1]) == 'csv')
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename,"r");
while(($data = fgetcsv($handle,1000,",")) != false)
{
$sql = "INSERT into employee(employee_code,employee_name,employee_address,emp_dateofjoin,emp_designation,emp_hq,pf_num,esic_num,emp_state,month,tot_work_days,lop_days,arrear_amt,leave_encash) values('$data[0]','$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]')";
/$upd = "UPDATE student SET month='',tot_work_days='',lop_days='',arrear_amt='',leave_encash='' where employee_code=''";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
Skip the first line by calling fgetcsv once before your loop:
fgetcsv($handle,1000,",");
while(($data = fgetcsv($handle,1000,",")) != false)
You also could use LOAD DATA INFILE MySQL statement with 'IGNORE 1 LINES' clause.
Related
I'm working on a website that required me to create function to upload .csv file.
When upload the file, it says wrong format, and it display this message:
C:\xampp\tmp\php9F4F.tmp
p/s:I already convert the excel file into .csv comma delimited format and still get error while uploading.
What should I do to resolve the error and then get to upload the csv file into my database?
stdreport.php : //im using the same code from import.php in here to connect it with database
<?php
$SQLSELECT = "SELECT stdCard, stdName, stdProgram, stdCourseDesc, stdCampus
FROM student
ORDER BY stdID
LIMIT 0,20";
$result_set = mysql_query($SQLSELECT, $conn);
while($row = mysql_fetch_array($result_set))
{
?>
import.php
<?php
$conn=mysql_connect("localhost","root","") or die("Could not connect");
mysql_select_db("dashboard",$conn) or die("could not connect database");
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0) {
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into student
(`stdID`, `stdCard`, `stdName`,
`stdOfficialEmail`,`stdEmail`,
`stdContNum`,`stdCourseDesc`, `stdCampus`,
`accessDate`)
values('$emapData[1]','$emapData[2]','$emapData[3]',
'$emapData[4]','$emapData[5]',
'$emapData[6]', '$emapData[7]','$emapData[8]',
'$emapData[9]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(! $result ) {
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"stdreport.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"stdreport.php\"
</script>";
//close of connection
mysql_close($conn);
}
}
?>
When you convert the excel file to CSV then there is two type of formate CSV UTF-8 (comma delimited ) and the second one is CSV (comma delimited ), use the second option I have also attached the screenshot.
I want to import the excel sheet data into mysql table with php but i am getting these errors someone please get me out from this.. please look on php code only ignore html stuff.
<?php
include ("connection.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[1];
$email = $filesop[2];
$sql = mysql_query("INSERT INTO co (name, email) VALUES ('$name','$email')");
$c = $c + 1;
}
fcose($file);
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recoreds";
}else{
echo "Sorry! There is some problem.";
}
}
?>
this is excel sheet
in database it is showing different format
There are libraries excellibrary/php-excel-reader/excel_reader2.php and excellibrary/SpreadsheetReader.php
you can use these libraries to read your content and convert it into array.
Once you convert your spreadsheet data into an array, you can easily insert into database using iterations.
here is my code to import csv data to my database
if (isset($_POST["submit"])) {
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
**while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];
$sql = mysql_query("INSERT INTO selleruser (emaili) VALUES ('$name')");
$c = $c + 1;
}**
if ($sql) {
echo "You database has imported successfully. You have inserted ". $c ." recoreds";
} else {
echo "Sorry! There is some problem.";
}
}?>
</div>
I have a csv file where there is a column which contains emails
the import is done suvcessfull but the issue is that it just imports the value in another format like in other language or encripted or something un readable
Try this query to import csv from phpmyadmin or any other mysql client
Before firing query, please make sure that table matching the fields is already created into db.
LOAD DATA LOCAL INFILE 'local machine path to csv file' INTO TABLE `selleruser`
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(emaili);
I'm trying to import data from my students.csv file into mysql using php. The entries in the csv file is in such a way that column (student_number, fname, lname, level) will be inserted into biodata table..
I'm also uploading the student.csv file from my computer.
When I run the page I dont get anything out on the screen.
session_start();
require('includes/dbconnect.php');
require 'includes/header.inc.php';
//check for file upload
if (isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
//upload directory
$upload_dir = "C:\Users\DOTMAN\Documents\students.csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
//open the csv file for reading
$handle = fopen($file_path, 'r');
//turn off autocommit and deletethe bio data
mysql_query("SET AUTOCOMMIT=0");
mysql_query("BEGIN");
mysql_query("TRUNCATE TABLE biodata") or die(mysql_error());
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
//Access field data in $data array ex.
$student_number = $data[0];
$fname = $data[1];
$lname = $data[2];
$level = $data[3];
//Use data to insert into db
$query = "INSERT INTO biodata (student_number, fname, lname, level)
VALUES ('$student_number', '$fname', '$lname', '$level')";
mysql_query($query) or die (mysql_error());
}
}
I'd suggest you to upload CSV-file with LOAD DATA INFILE command. This is fast method.
if you only need to do this once, i would consider using something like: http://csv2sql.com/
One immediate issue I can see is here:
$upload_dir = "C:\Users\DOTMAN\Documents\students.csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
You are already assigning the entire path, including the file name, to the $upload_dir variable - and then you're appending the uploaded file name again.
If you think there are errors in your code, start by adding
ini_set('display_errors', 1);
error_reporting(E_ALL);
to the beginning of your PHP code and fix any warnings/errors displayed. You can then turn off printing error messages by changing the second parameter to 0 in the first call.
Have u debug the $_FILES:
print_r($_FILES);
before doing any thing
Solution using PHP
$file = 'path/to.csv';
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
echo $column1.$column2."<br />";
//put the mysql insert statement here
}
I am using the following script to import data into my mysql database from CSV files. The CSV is setup like this :
Name Postcode
fred hd435hg
bob dh345fj
Above is what it looks like in excel, in raw csv format viewed in notepad it looks like this :
name,postcode
frank,ng435tj
The problem I am having is for some reason the postcode column isnt getting imported at all, also the header row is getting imported as a record too, is it possible to make it skip the first row ?. I have been through the code and cant see why the postcode is not being pulled in, it is very odd.
<?php
//database connect info here
//check for file upload
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//upload directory
$upload_dir = "./csv";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
//open the csv file for reading
$handle = fopen($file_path, 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
//Access field data in $data array ex.
$name = $data[0];
$postcode = $data[1];
//Use data to insert into db
$sql = sprintf("INSERT INTO test (name, postcode) VALUES ('%s',%d)",
mysql_real_escape_string($name),
$postcode
);
mysql_query($sql) or (mysql_query("ROLLBACK") and die(mysql_error() . " - $sql"));
}
//delete csv file
unlink($file_path);
}
?>
Your CSV file seems to be a TSV file actually. It doesn't use commas, but tabulators for separating the fields.
Therefore you need to change the fgetcsv call. Instead of ',' use the tab:
while (($data = fgetcsv($handle, 1000, "\t") ...
And to also skip the header row, add another faux fgetcsv before the while block:
fgetcsv($handle);
while (...) {
That will skip the first line. (A simple fgets would also do.)
Oh, just noticed: The postcode might also get dropped because you concat it into the string as decimal with the sprintf placeholder %d for $postcode. Should that field actually contain lettery, like in your example, then that wouldn't work. -- Though I presume that's just a wrong example printout.
Try this one.
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$username = $fileop[0];
$name = $fileop[1];
$address = $fileop[2];
$sql = mysql_query("INSERT INTO ...... ");
}