How to insert csv file data into database? - php

Currently I am doing a project in php for uploading CSV file and to insert data into database.After CSV file uploaded it displays the data present in file with checkboxes.On Clicking the checkbox the values are not getting inserted into the table.
The Coding I used
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
echo("<table border='1'>");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
echo("<tr>\r\n");
foreach ($data as $index=>$val)
{
echo("\t<td><input type='checkbox' name='chk1[]' value='$val'>$val</td>\r\n");
}
}
echo("</tr>\r\n");
echo("</table>");
echo("<input type='submit' name='insert' id='insert' value='Submit' />");
fclose($handle);
}
On Uploading the file the values get displayed,but clicking on submit button no action is performed.
The Code for Submit button is:
if(isset($_POST['insert']))
{
for($i=0;$i < sizeof($checkbox1);$i++)
{
$query = "INSERT INTO uploadmail (name,email) VALUES ('$name','".$checkbox1[$i]."')";
$result = mysql_query($query);
}
}
The values displayed like this
Please give your suggestions.THANKS IN ADVANCE.

You can download reader.php and oleread.inc zip folder from this site http://sourceforge.net/projects/phpexcelreader/
and rest of code to insert data in database
require_once 'Excel/reader.php';
// ExcelFile($filename, $encoding);
$data = new Spreadsheet_Excel_Reader();
// Set output Encoding.
$data->setOutputEncoding('CP1251');
$data->read($_FILES['excel_upload']['tmp_name']);
error_reporting(E_ALL ^ E_NOTICE);
for ($i=1;$i<=$data->sheets[0]['numRows'];$i++)
{
$EmailAdd = $data->sheets[0]['cells'][$i][1];
$NameAdd = $data->sheets[0]['cells'][$i][2];
$Phone = $data->sheets[0]['cells'][$i][3];
$Address = mysql_real_escape_string($data->sheets[0]['cells'][$i][4]);
if(filter_var($EmailAdd, FILTER_VALIDATE_EMAIL))
{
$currentId = mysql_query("INSERT INTO `Student` (`StudentEmail_email`,StudentEmail_Name`,`StudentEmail_Mobile`,`StudentEmail_Address`) VALUES ('$EmailAdd','$NameAdd','$ContactAdd','$Address')");
}
}

Remarks:
I have included some explanations in the code quoted in /* */.
I changed your insert query to MySQLi Prepared Statement rather than the
deprecated MySQL.
Here's a code that you can use.
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = file_get_contents($_FILES['filename']['tmp_name']); /* GET THE CONTENT OF UPLOADED FILE */
$val = explode(',',$handle);
$count = count($val); /* COUNT THE TOTAL EXPLODED RESULT */
echo("<table border='1'>");
for($x=0;$x<=$count;$x++){ /* START THE LOOP BASED FROM THE COUNTED RESULT */
echo("<tr>\r\n");
echo("\t<td><input type='checkbox' name='chk1[$x]' value='$val[$x]'>$val[$x]</td>\r\n"); /* GET THE VALUE AND STORE IT INTO THE chk1 ARRAY */
echo("</tr>\r\n");
} /* END OF FOR LOOP */
echo("</table>");
echo("<input type='submit' name='insert' id='insert' value='Submit' />");
} /* END OF ISSET UPLOAD */
I just noticed that you don't have the move_uploaded_file. Or you just didn't include it in your sample code?
And after selecting/checking the check boxes and submitting the form:
if(isset($_POST['insert']))
{
$comp=count($_POST['chk1']); /* COUNT THE TOTAL SUBMITTED CHECKBOX */
$checkbox1=$_POST['chk1'];
for($i=0;$i<=$comp;$i++)
{
if(!empty($checkbox1[$i])){ /* IF SUBMITTED DATA IS CHECKED */
/* WHERE DOES YOUR $name VARIABLE CAME FROM? */
$stmt = $YourSQLConnection->prepare("INSERT INTO uploadmail (name,email) VALUES (?, ?)");
$stmt->bind_param('ss', $name,$checkbox1[$i]); /* BIND THE VALUE TO STRINGS */
}
}
}

Related

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!

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.");
?>

To Insert Checkbox Values into Database

Currently I am doing a project in php for uploading CSV file and to insert data into database. Before Inserting I need to display the data in checkboxes and to insert the values that are checked.
With this code after uploading it displays data with checkbox but on clicking the checkbox the values are not inserting into database.
if(isset($_POST['upload']))
{
if (is_uploaded_file($_FILES['filename']['tmp_name']))
{
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
echo("<table border='1'>");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
echo("<tr>\r\n");
foreach ($data as $index=>$val)
{
echo("\t<td><input type='checkbox' name='chk1[]' value='$val'>$val</td>\r\n");
}
echo("</tr>\r\n");
}
echo("</table>");
echo("<td><input type='submit' name='insert' id='insert' value='Submit' /></td>");
fclose($handle);
}
For Inserting the selected data into database I am using this code.
if(isset($_POST['insert']))
{
for($i=0;$i < sizeof($checkbox1);$i++)
{
$query = "INSERT INTO uploadmail (name,email) VALUES ('$name','".$checkbox1[$i]."')";
echo $query;
$result = mysql_query($query);
}
}
After clicking checkboxes when I click Submit button it is not doing any action.So Please give me any suggestions.
THANKS IN ADVANCE.
Your table closed before the form submit. And please maintain the table structure if you are using form in a table. Close all input fields in table's td followed by "tr".
And here its understood that you assigned $checkbox1 = $_POST['chk1'];

How to check before upload a CSV file to MySQL db if user has selected one

I have simple script that uploads CSV files to a MySQL database. It works ok but if user misses selecting some CSV file to upload and pushes the UPLOAD button, the script tries to insert thousand of 0 lines in the data base.
I wonder if there is a way to check befoere upload file if user has allready selected FILE.
Here is my code:
<?php
include("conection.php"); //Connect to Database
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$count = 0; //skip first line of the CSV file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if($count) //skip first line of the CSV file
{
$import="INSERT into PAX (name,surname,group) VALUES('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
$count++;
}
fclose($handle);
print "<br><center><p>UPLOADED </p></center> ";
print "<br> ";
print "<center><a href='index.php'><button>HOME</button</a></center> ";
//view upload form
}else {
print "<center><br><p><b>UPLOAD</b> </p>\n";
print "<center><br>Select the file for Upload \n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
?>
Hard to say definitively with your code as it is presented & without seeing the original data, but I believe simply setting a conditional that checks $data is enough to prevent the issue you are seeing:
So this line:
if ($count) //skip first line of the CSV file {
Changes to this:
if ($count && !empty($data)) //skip first line of the CSV file {
And here is your code adjusted and indents cleaned up for readability. EDIT And I have edited it so there is now a $SUCCESS_SUBMIT variable. That way if the submission is successful & that is true or false you can act on it.
include("conection.php"); //Connect to Database
$SUCCESS_SUBMIT = false;
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$count = 0; //skip first line of the CSV file
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
if ($count && !empty($data)) //skip first line of the CSV file {
$import = "INSERT into PAX (name,surname,group) VALUES('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
$SUCCESS_SUBMIT = true;
}
$count++;
}
fclose($handle);
}
if ($SUCCESS_SUBMIT) {
print "<br><center><p>UPLOADED </p></center> ";
print "<br> ";
print "<center><a href='index.php'><button>HOME</button</a></center> ";
}
else {
print "<center><br><p><b>UPLOAD</b> </p>\n";
print "<center><br>Select the file for Upload \n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
"There is a way to show user if hasnt selected any csv file give a message file "please select file" or something like this"
you could use javascript to have a message, if not file selected:
print "<form enctype='multipart/form-data' action='upload.php'
onsubmit='return validateUpload();' name='formUpload'
method='post'>";
print "<center><input size='50' type='file' name='filename'><br />\n";
print "<br>";
print "<input type='submit' name='submit' value='UPLOAD'></form>";
}
?>
<script type="text/javascript" >
function validateUpload()
{
var fName = document.forms["formUpload"]["filename"].value;
if (fName==null || fName=="")
{
alert("Please select file !");
return false;
}
}
</script>

Import CSV, exclude first row

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

Categories