Uploading Csv Not Working after Modification - php

<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['sess_user_id']) || (trim($_SESSION['sess_user_id']) == '')) {
header("location: index.php");
exit();
}
include ("../config.php");
if(isset($_POST["Import"]))
{
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1";
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$sql="INSERT INTO client (fid, fname, mname, lname, address, contact_num, category, bank, card_num, pin_num, salary_sched, salary, stat) VALUES
('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]','$emapData[8]','$emapData[9]','$emapData[10]','$emapData[11]','$emapData[12]')";
$res=$con->query($sql);
// $res=$con2->query($sql);
}
fclose($file);
echo 'CSV File has been successfully Imported';
}
else
echo 'Invalid File: Please Upload CSV File';
}
header("Location: ../clerk.php");
?>
I only copied these on my other php file and it is working. But I do not understand why it is not after modifying adding $emapData
Can someone please help me?
Heres the sample of the first fIle which is working.
<?php
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['sess_user_id']) || (trim($_SESSION['sess_user_id']) == '')) {
header("location: index.php");
exit();
}
include ("../config.php");
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)
{
//print_r($emapData);
//exit();
$sql = "INSERT INTO grades (stud_id, code, sub_desc, units, year, sem, prof, grade) VALUES
('$emapData[0]',
'$emapData[1]',
'$emapData[2]',
'$emapData[3]',
'$emapData[4]',
'$emapData[5]',
'$emapData[6]',
'$emapData[7]')";
$res=$con->query($sql);
// $res=$con2->query($sql);
}
fclose($file);
echo 'CSV File has been successfully Imported';
}
else
echo 'Invalid File: Please Upload CSV File';
}
header("Location: ../success.php");
?>

Related

Import CSV file with auto generate code to MySQL database

I just want to ask if how can I import a CSV file to MySQL database with an auto-generated QR code? I can now import CSV file to database however I can't make it work with the QR code.
Here's the working code for importing a CSV file.
$conn = getdb();
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE){
$sql = "INSERT into users (name)
values ('".$getData[0]."')";
$result = mysqli_query($conn, $sql);
if(!isset($result)){
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"ad-bulk.php\"
</script>";
} else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"ad-bulk.php\"
</script>";
}
}
fclose($file);
}
}
And this is the code that I'm using to generate a QR code. I already tried this code if my approach is to to add user one by one. However, I need to import a bulk of data.
$uniqueid = uniqid('IT-');
$text = $uniqueid;
$path = '../temp/';
$file_name= $path.$uniqueid.".png";
$ecc = 'L';
$pixel_Size = 20;
$frame_Size = 1;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file_name, $ecc, $pixel_Size, $frame_Size);
I tried this approach but it is not working..
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
$uniqueid = uniqid('IT-');
$text = $uniqueid;
$path = '../temp/';
$file_name = $path.$uniqueid.".png";
$ecc = 'L';
$pixel_Size = 20;
$frame_Size = 1;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file_name, $ecc, $pixel_Size, $frame_Size);
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE){
$sql = "INSERT into users (code, name)
values ($text,'".$getData[0]."')";
$result = mysqli_query($conn, $sql);
if(!isset($result)){
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"ad-bulk.php\"
</script>";
} else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"ad-bulk.php\"
</script>";
}
}
fclose($file);
}
}
This is the solution that I came up with. Thank you!
$conn = getdb();
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE){
$uniqueid = uniqid('IT-');
$text = $uniqueid;
$path = '../temp/';
$file_name = $path.$uniqueid.".png";
$ecc = 'L';
$pixel_Size = 20;
$frame_Size = 1;
// Generates QR Code and Stores it in directory given
QRcode::png($text, $file_name, $ecc, $pixel_Size, $frame_Size);
echo $getData[0] . "<br>";
echo $text . "<br>";
$sql = "INSERT into users (code, name)
values ('$text','".$getData[0]."')";
echo $sql . "<br>" ;
$result = mysqli_query($conn, $sql);
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"ad-bulk.php\"
</script>";
}
else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"ad-bulk.php\"
</script>";
}
}
fclose($file);
}
}

Upload a CSV file via PHP and Insert Into MySQL DB

No error messages appear on the page. Upload File button works. Upload button doesn't trigger db insert but the page refreshes as if it did.
I am not sure if the array of data from Excel is being coded correctly on the INSERT Into command. Any help is appreciated but PLEASE keep it simple. I am not a seasoned developer. Very green and primarily use procedural coding. If you use an experienced term, don't assume I know what it means.
PHP - if Post Submit button code. The errorMsg doesn't display if no file is attached and submit button is clicked
var_dump($_POST);
if (isset($_POST['submit'])) {
//print_r($_FILES);
$ok = 'true';
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
echo ++$x;
if ($handle !== FALSE){
$errorMsg = "<br /><div align='center'><font color='red'>Please select a CSV file to import</font></div>";
$ok = 'false';
echo ++$x;
PHP continued - I'm not seeing the uploaded file populate the database
} else {
print_r(fgetcsv($handle));
while(($filesop = fgetcsv($handle, 1000, ",")) !== FALSE){
$email = mysqli_real_escape_string($con_db, $filesop[0]);
$f_name = mysqli_real_escape_string($con_db, $filesop[1]);
$l_name = mysqli_real_escape_string($con_db, $filesop[2]);
$password = md5(mysqli_real_escape_string($con_db, $filesop[3]));
$zipcode = mysqli_real_escape_string($con_db, $filesop[4]);
$co_id = mysqli_real_escape_string($con_db, $filesop[5]);
$employee = mysqli_real_escape_string($con_db, $filesop[6]);
$assessment_ct = mysqli_real_escape_string($con_db, $filesop[7]);
echo ++$x;
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if ( strlen($email) > 0) {
echo ++$x;
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo ++$x;
$ok = 'false';
$errorMsg .= 'E-mail address is not correct';
}
}
// error handling for password
if (strlen($password) >= 5) {
echo ++$x;
$ok = 'true';
} else {
echo ++$x;
$ok = 'false';
$errorMsg .= 'Your password is too short (please use at least 5 characters)';
}
// If the tests pass we can insert it into the database.
if ($ok == 'true') {
echo ++$x;
$sql = mysqli_query($con_db, "INSERT INTO `myMembers` (email, f_name, l_name, password, zipcode, co_id, employee, assessment_ct) VALUES ('$email', '$f_name', '$l_name', '$password', '$zipcode', '$co_id', '$employee', '$assessment_ct')") or die ("Shit is not working");
} else {// close if $ok == 'true'
$result = print_r($handle);
echo $handle.'<br>';
echo ++$x;
}
} // close WHILE LOOP
fclose($handle);
if ($sql !== FALSE) {
echo ++$x;
$successMsg = 'Your database has imported successfully!';
//print_r($_FILES);
//header('excel_import.php');
} else {
echo ++$x;
$errorMsg = 'Sorry! There is some problem in the import file.';
//print_r($_FILES);
//header('excel_import.php');
}
} // close if (!is_null($file)){
} // close if $post = submit
HTML Code for the form to submit uploaded file
<form enctype="multipart/form-data" method="POST" action="excel_import.php">
<div align="center">
<label>File Upload: </label><input type="file" id="csv_file" accept=".csv" >
<p>Only Excel.CSV File Import</p>
<input type="submit" name="csv_file" class="btn myButton" value="Upload">
</div>
</form>
</div>
<div><?php echo $errorMsg; ?><?php echo $successMsg; ?></div>
Your submit button does not have a name - and thus $_POST['submit'] is not set. Also, fclose($file) should be fclose($handle). And you should be checking with $handle !== FALSE and $sql !== FALSE rather than with is_null().

excel file upload to database using Php

I am trying to upload excel .xls file but got an error when I am trying to import autoload file my web page going blank and when I comment it its works. I can't Import file of spout extenstion of reader. Here this is my code.
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;
require_once 'http://localhost/muddy/admin/spout-2.7.2/src/Spout/Autoloader/autoload.php';//Error cant import
here in this require once cant upload file if I write this code my web page going blank !
if (!empty($_FILES['file']['name'])) {
echo "ks";
$pathinfo = pathinfo($_FILES["file"]["name"]);
if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
&& $_FILES['file']['size'] > 0 ) {
$inputFileName = $_FILES['file']['tmp_name'];
// Read excel file by using ReadFactory object.
$reader = ReaderFactory::create(Type::XLSX);
// Open file
$reader->open($inputFileName);
$count = 1;
foreach ($reader->getSheetIterator() as $sheet) {
echo "ks22";
// Number of Rows in Excel sheet
foreach ($sheet->getRowIterator() as $row) {
echo "ks32";
// It reads data after header. In the my excel sheet,
// header is in the first row.
if ($count > 1) {
echo "ks4";
// Data of excel sheet
$data['Member_no'] = $row[0];
$data['Member_name'] = $row[1];
$data['Gender'] = $row[2];
$data['Club_name'] = $row[3];
$data['member_since'] = $row[4];
$data['Expiry_date'] = $row[3];
$member_no = $data['Member_no'];
$member_name = $data['Member_name'];
$gender = $data['Gender'];
$club_name = $data['Club_name'];
$member_since = $data['member_since'];
$expiry_date = $data['Expiry_date'];
$query="INSERT INTO `mmholdin_management`.`Club_member` (Member_no`, `Member_name`, `Gender`, `Club_name`, `member_since`, `Expiry_date`) VALUES ($member_no ,$member_name, $gender,$club_name,$member_since,$expiry_date)";
echo $query;
if(mysql_query($query))
{
$msg = "Record Saved!";
//header("Location:managecustomer.php");
exit;
}
else
{
$msg = "Unable to Save!";
}
print_r(data);
}
$count++;
}
}
// Close excel file
$reader->close();
} else {
echo "Please Select Valid Excel File";
}
} else {
//echo "Please Select Excel File";
}
try this example.
$file = "your-file.xls";
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$name = $filesop[0];
$email = $filesop[1];
$sql = mysql_query("INSERT INTO xls (name, email) VALUES ('$name','$email')");
}
if($sql){
echo "You database has imported successfully";
}else{
echo "Sorry! There is some problem.";
}
check this: https://www.studytutorial.in/how-to-upload-or-import-an-excel-file-into-mysql-database-using-spout-library-using-php

How to upload excel file to mysql in php

I am trying to upload an excel file using the HTML input tag, to MySQL database using PHP. But the result is a whole lot of characters in the database. the only time it works correctly is when I create a .csv file with notepad and upload it.
if(isset($_POST['submit_excel'])){
if(!is_uploaded_file($_FILES['file_excel']['tmp_name'])){
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup_no_f").style.visibility = "hidden"; } document.getElementById("popup_no_f").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
} else {
$filename = $_FILES['file_excel']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
if ($extension == 'xlsx' || $extension == 'csv' || $extension == 'xls') {
if($_FILES['file_excel']["size"] > 0)
{
$handle = fopen($_FILES['file_excel']['tmp_name'], "r");
$count = 0;
while (($data = fgetcsv($handle, 1024, ",")) !== FALSE)
{
$count++;
if ($count>1) {
if (empty(data[0]) && empty(data[1]) && empty(data[2]) && empty(data[3]) && empty(data[4]) ){
echo alert();
}else{
do{
$bookuniqueid = uniqueid();
$query = "SELECT book_unique_id FROM books_tbl WHERE book_unique_id= '$bookuniqueid' ";
$query_run = mysqli_query($link, $query);
$numRowsCheck = mysqli_num_rows($query_run);
} while ( $numRowsCheck > 0);
$import ="INSERT INTO books_tbl (book_name, book_authors, book_category, book_quantity, book_cd, book_unique_id, book_uploaded_admin, book_created_date, book_quant_stat) VALUES ('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]', '$bookuniqueid', '$adminname', current_date, '$data[3]' )";
mysqli_query($link, $import);
}
}
}
fclose($handle);
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup").style.visibility = "hidden"; } document.getElementById("popup").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
}
} else {
echo '<script type="text/javascript">function hideMsg(){
document.getElementById("popup_ext").style.visibility = "hidden"; } document.getElementById("popup_ext").style.visibility = "visible";
window.setTimeout("hideMsg()", 4000);
</script>';
}
}

Import CSV data to fields in MySQL Database

I am trying to upload a CSV file which contains the fields stated in the link below [see CSV example] via a web form. The user can browse their computer by clicking the upload button, select their CSV file and then click upload which then imports the CSV data into the database in their corresponding fields. At the moment when the user uploads their CSV file, the row is empty and doesn't contain any of the data that the CSV file contains. Is there a way i could solve this so that the data inside the CSV file gets imported to the database and placed in its associating fields?
CSV example:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-04-10at145431_zps80a42938.png
uploads.php
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
upload_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$filedata= file_get_contents($_FILES ['uploaded_file']['tmp_name']); //this imports the entire file.
// Create the SQL query
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'{$date}', '{$order_ref}', '{$postcode}', '{$country}', '{$quantity}', '{$packing_price}', '{$dispatch_type}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
try this
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
$file = $_FILES ['uploaded_file']['tmp_name'];
$handle = fopen($file, "r");
$row = 1;
while (($data = fgetcsv($handle, 0, ",","'")) !== FALSE)
{
if($row == 1)
{
// skip the first row
}
else
{
//csv format data like this
//$data[0] = date
//$data[1] = order_ref
//$data[2] = postcode
//$data[3] = country
//$data[4] = quantity
//$data[5] = packing_price
//$data[6] = dispatch_type
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '".$data[4]."', '".$data[5]."', '".$data[6]."', NOW()
)";
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
$row++;
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
fgetcsv() in third argument in separator to you want to save in csv file. Ex: comma,semicolon or etc.
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$filedata= csv_to_array($_FILES ['uploaded_file']['tmp_name']);
foreach($filedata as $data)
{
$sql = "INSERT into table SET value1='".$data['value1']."'......";
}

Categories