Improve Upload of CSV File
I would really like some help in improving this code that
I paid someone to write. (Or replacing it altogether.)
The part I want to improve now is the "upload of a CSV file"
code.
Sometimes it works and sometimes it says "Invalid file".
The next day it will upload that same file, so, it was not
really an "Invalid file". It has other problems as well.
The complete file, MANAGE-USER.PHP, has a lot in it and I
would really like to slim it down.
It has PHP code at the top and a HTML DOC file at the bottom.
There are two JS script calls from within MANAGE-USER.PHP.
There are outside PHP files that make connection to the
database and tables and get the user logged-in.
Since I have limited characters that I can post here, I am
going to post snipets of the "upload of a CSV file" code.
Any help would be appreciated. 🙂
Here is the code:
//CHECK FILE FORMAT
if (isset($_FILES["file"]["name"])) {
if ($_FILES["file"]["name"] != "") {
//UPLOAD FILE
<?php
$rest = substr($_FILES["file"]["name"], -3);
$_FILES["file"]["name"] = time() . $_FILES["file"]["name"];
if ((($_FILES["file"]["type"] == "text/octect-stream") || ($rest == "csv") || ($rest == "CSV")) && ($_FILES["file"]["size"] < 20000)) {
if ($_FILES["file"]["error"] > 0) {
$ERR = "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
$ERR.= "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
$ERR.= "Stored in: " . "upload/" . $_FILES["file"]["name"];
$uploaddie = "upload/" . $_FILES["file"]["name"];
}
} else {
$ERR.= "Invalid file";
}
?>
} else $ERR = 'Please Enter a CSV File.';
}
//FUNCTION FOR UPLOAD USER DATA
function CSVImport($table, $csv_fieldname = 'csv') {
if (!$csv_fieldname) return;
$handle = fopen($csv_fieldname, 'r');
//print($handle);
if (!$handle) die('Cannot open uploaded file.');
$fields = fgetcsv($handle, 1000, ",");
$userfield = $fields[1];
$emailfield = $fields[5];
$c = count($fields) - 1;
if ($fields[$c] == '') unset($fields[$c]);
unset($fields[0]);
$row_count = 0;
$rows = array();
//Read the file as csv
$update = 0;
$insert = 0;
mysql_query("TRUNCATE TABLE `user_backup`") or die(mysql_error());
mysql_query("insert into user_backup(select * from user)");
mysql_query("TRUNCATE TABLE `user`");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row_count++;
foreach($data as $key => $value) {
$data[$key] = "'" . addslashes($value) . "'";
}
unset($data[0]);
$rows[0] = implode(",", $data);
//print_r($data);
$username = trim($data[1]);
$email = trim($data[5]);
$insert++;
$sql_query2 = "INSERT INTO $table(" . implode(',', $fields) . ") VALUES(" . implode("),(", $rows) . ")";
$query = mysql_query($sql_query2);
}
if ($query == false) {
$ERR = "Incorrect format or wrong file selection for importing.";
mysql_query("TRUNCATE TABLE `user`") or die(mysql_error());
mysql_query("insert into user(select * from user_backup)");
mysql_query("TRUNCATE TABLE `user_backup`");
}
$MSG = "<br>TOTAL RECORDS INSERTED " . $insert . '';
if (isset($ERR)) {
$MSG = $ERR;
}
fclose($handle);
return ($MSG);
}
//END OF FUNCTION
//
if (isset($uploaddie)) {
$MSG = CSVImport('user', $uploaddie);
header("location:manage-user.php?message=$MSG");
}
//
//********************************************
//INCLUDE FILES FOR SET LIMIT FOR NUMBER OF RECORDS
include ("rows_admin.php");
$lookup = ($_POST['lookup']) ? $_POST['lookup'] : $_GET['lookup'];
if ((isset($_POST['lookup'])) or ($_GET['lookup'] != "")) {
//QUERY WHEN CLICK ON LOOKUP BUTTON
// dp: removed userType <>'Admin' from where clause
$query1 = "SELECT COUNT(id) AS numrows FROM " . TABLE_USER . " WHERE lastname LIKE '%" . $lookup . "%'";
} else {
//QUERY FOR FETCH NUMBER OF RECORDS
// dp: removed userType <>'Admin' from where clause
$query1 = "SELECT COUNT(id) AS numrows FROM " . TABLE_USER;
}
$result1 = mysql_query($query1) or die('Error, query failed');
$row1 = mysql_fetch_array($result1, MYSQL_ASSOC);
$numrows = $row1['numrows'];
if ($numrows == 0) {
$error[] = 'No Record Found..!';
}
$offset = ($page_num - 1) * $rowperpage;
if ((isset($_POST['lookup'])) or ($_GET['lookup'] != "")) {
//QUERY FOR FETCH USER RECORDS USING LASTNAME SHORTING
// dp: removed userType <>'Admin' from where clause
$query = "SELECT * FROM " . TABLE_USER . " WHERE lastname LIKE '%" . $lookup . "%' order by $order $type limit $offset,$rowperpage";
} else {
//QUERY FOR FETCH USER RECORDS.
// dp: removed userType <>'Admin' AND from where clause
$query = "SELECT * FROM " . TABLE_USER . " order by $order $type limit $offset,$rowperpage";
}
$result = mysql_query($query);
if ((isset($_GET['ltype'])) and (isset($_GET['orderby']))) $pa = "&orderby=" . $order . "<ype=" . $type;
//INCLUDE PAGING FOR THE PAGE
include ("paging.php");
if (isset($_GET['page'])) {
$pages = $_GET['page'];
$p = "&page=" . $pages;
} else {
$p = '';
}
if (isset($_GET['message'])) {
$MSG = $_GET['message'];
}
?>
<!--
****************************************
* The following HTML DOC contains the
* type="file"
* which makes a browse button to pick the CSV file to upload.
****************************************
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>
Work Hours Tracker
</title>
<tr>
<td colspan="5" nowrap="nowrap">
<table align="left" width="50%" border="0">
<tr>
<td width="22" align="left" nowrap="nowrap">
File :
</td>
<td width="258" align="left">
<!--<input style="*border:solid 1px #000000;" type="file" class="button1" name="file" size="22">-->
<input type="text" id="fileName" class="file_input_textbox" />
<div class="file_input_div" style="border: 0px coral solid;">
<input type="button" value="Browse" class="file_input_button" />
<input type="file" name="file" class="file_input_hidden" onchange="javascript: document.getElementBy
</div>
</td>
</tr>