Import CSV, exclude first row - php

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

Related

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.

How to Validate Employee Id in Importing File in .CSV format to SQL?

How to Validate Employee Id in Importing File in .CSV format to SQL?
*a code that check if the data is already exist.
-->sample: if the Employee Id already exist it promts "Employee ID already Exist"..
if the rows in csv, you can make a array of csv rows.
$list =array();
$id = array();
while( ($rows= getcsv($hande)) !== false)
{
array_push($list, $rows);
array_push($id, $rows['emplyee_id']);
}
then check mysql or database
$check_id = implode(",", $id);
$que = "select employ_id from table where employ_id in ($check_id)";
at this time you can find employ_ids from database.
if you make employee_id column unique, your code would be like this
$result=mysqli_query($db_con", "insert into table (employ_id) values ('$empoy_id')";
if($result == false) // if employ_id alreay exists in table $result is false
{
}
but as i know, the best way using index is checking key is exists before inserting data not after inserting query failed.
This is my code:
`<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
echo $a;
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('cgi_warehouse',$connect);
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];
$col5 = $slice[4];
$col6 = $slice[5];
$col7 = $slice[6];
$col8 = $slice[7];
$col9 = $slice[8];
$col10 = $slice[9];
$col11 = $slice[10];
$col12 = $slice[11];
$col13 = $slice[12];
$col14 = $slice[13];
$col15 = $slice[14];
$col16 = $slice[15];
$query = "INSERT INTO tools(tools_id, item_description, category_id, sn, qty, price, supplier, frm, location, ref_no, sender, receiver, date_receive, date_added, status, remarks) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."','".$col12."','".$col13."','".$col14."','".$col15."','".$col16."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully uploaded.');window.location.href='#';</script>";
mysql_close($connect);
}
?>`

Import particular Colums of csv in database in php/sql

I have a CSV which contains 15 columns.
But I want to import only 2 columns from the CSV in database.
whats should I do?
I tried importing but it's importing all the columns.
<?php
//database connection details
$connect = mysql_connect('localhost','root','123456');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('test',$connect);
// path where your CSV file is located
define('CSV_PATH','C:/wamp/www/');
// Name of your CSV file
$csv_file = CSV_PATH . "test.csv";
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
$col1 = $col[0];
$col2 = $col[1];
$col3 = $col[2];
// SQL Query to insert data into DataBase
$query = "INSERT INTO csvtbl(ID,name,city) VALUES('".$col1."','".$col2."','".$col3."')";
$s = mysql_query($query, $connect );
}
fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);
?>

Strip "$" from csv file

I have a php page that takes in a csv file and uploads it to my database. The issue I am having is that some of the fields have a '$' which i do not need. Is there a way to remove the $ from only some of the fields?
Data structure
COLL_ID COCC_ID AGEDTOTAL PAYMENTTOTAL
5074 11110 $7.50 ($7.50)
my Query
$deleterecords = "TRUNCATE TABLE mytable"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
$i=0;
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 mytable(COLL_ID, COCC_ID, AGEDTOTAL, PAYMENTTOTAL) values('$data[0]','$data[1]','$data[2]','$data[3]')";
mysql_query($import) or die(mysql_error());
}
$i++;
}
For the whole file
$string = preg_replace(
'/((:?.*?\,){2}.*?)\$/',
'$1',
$string
);
2 is a ((Number of column that contains $ symbol) - 1)
or
$data[2] = str_replace('$', '', $data[2]);

Insert with php in mysql from CSV if not exists

I got a problem and could't find a solution for me.
I want to insert with a php script in my mysql database from a csv file.
The database got a primary key, which is created automatically on every insert.
The csv file grows with time, but the existed date should not be inserted again! I could not check the primary key in this case, because it is generated on every insert.
This is my file so far:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT INTO xt_products(
products_owner,
products_quantity,
products_shippingtime,
products_model,
products_model_original,
products_price,
products_tax_class_id
) VALUES (
'$data[0]',
'$data[1]',
'$data[2]',
'$data[3]',
'wayne_$data[4]',
'$data[5]',
'$data[6]'
)";
mysql_query($import) or die (mysql_error());
}
I know about where exists or if exists bgin end, but I could not get it to work.
Edit: Forgot to mention it, it should check, whether the products_model is already in the database. That would be the $data[3] field there
You just have to add the duplicate statement
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import = "INSERT INTO xt_products(
products_owner,
products_quantity,
products_shippingtime,
products_model,
products_model_original,
products_price,
products_tax_class_id
) VALUES (
'$data[0]',
'$data[1]',
'$data[2]',
'$data[3]',
'$data[4]',
'$data[5]',
'$data[6]'
)
ON DUPLICATE KEY UPDATE products_owner='$data[0]'
";
mysql_query($import) or die (mysql_error());
}
<?php
include ("config.php"); //Connect to Database
//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 table(something,something,something,something,something,something,something) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]')";
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='import.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>";
}
?>
config.php
<?php
$db = mysql_connect('localhost', 'user', 'pass') or die("Could not connect.");
if(!$db)
die("no db");
if(!mysql_select_db("database",$db))
die("No database selected.");
?>

Categories