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>