Import CSV file with auto generate code to MySQL database - php

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

Related

PHP Why the imported csv file only insert the first row of csv to SQL

Let's say I have 3 row in the .csv file with 3 column. In that case I need to import the exact same file for 3 times to get all my data in the .csv file to completely inserted into my SQL database. I thought !feof($file) should make sure the looping through the end of file?
if (isset($_POST['submitI'])){
$filename = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while (!feof($file)){
$getData = fgetcsv($file, '0');
$sql = "SELECT * FROM murid WHERE No_Sek_Murid = '".$getData[0]."'";
$result = mysqli_query($conn, $sql);
if(empty($getData[0] || $getData[1] || $getData[2])){
$errorForm = "Sila isikan semua medan dalam fail!";
echo "<script type='text/javascript'>alert('$errorForm');</script>";
echo "<script> location.href='../main.php'; </script>";
exit();
}
if(mysqli_num_rows($result) === 0){
$sqlMurid = "INSERT INTO murid (No_Sek_Murid, Nama_Murid, Kelas_Murid) VALUES ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."')";
$sqlKelab = "INSERT INTO kelab (Kod_Kelab, No_Sek_Murid, ID_Pengguna) VALUES ('{$_SESSION['kodKelab']}', '".$getData[0]."', '{$_SESSION['username']}')";
mysqli_query($conn, $sqlMurid);
mysqli_query($conn, $sqlKelab);
$success = "Berjaya menambah rekod ke dalam pangkalan data!";
echo "<script type='text/javascript'>alert('$success');</script>";
echo "<script> location.href='../main.php'; </script>";
exit();
}
} fclose($file);
} else {
$errorfile = "Operasi import gagal!";
echo "<script type='text/javascript'>alert('$errorfile');</script>";
echo "<script> location.href='../main.php'; </script>";
exit();
}
}
Don't use exit() unnecessarily. Also you passed multiple parameters to empty() function which seems incorrect. You can run your code without exit function as below:
if (isset($_POST['submitI'])){
$filename = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0){
$file = fopen($filename, "r");
while (!feof($file)){
$getData = fgetcsv($file, '0');
$sql = "SELECT * FROM murid WHERE No_Sek_Murid = '".$getData[0]."'";
$result = mysqli_query($conn, $sql);
if(empty($getData[0]) || empty($getData[1]) || empty($getData[2])){
$errorForm = "Sila isikan semua medan dalam fail!";
echo "<script type='text/javascript'>alert('$errorForm');</script>";
echo "<script> location.href='../main.php'; </script>";
} elseif(mysqli_num_rows($result) === 0){
$sqlMurid = "INSERT INTO murid (No_Sek_Murid, Nama_Murid, Kelas_Murid) VALUES ('".$getData[0]."', '".$getData[1]."', '".$getData[2]."')";
$sqlKelab = "INSERT INTO kelab (Kod_Kelab, No_Sek_Murid, ID_Pengguna) VALUES ('{$_SESSION['kodKelab']}', '".$getData[0]."', '{$_SESSION['username']}')";
mysqli_query($conn, $sqlMurid);
mysqli_query($conn, $sqlKelab);
$success = "Berjaya menambah rekod ke dalam pangkalan data!";
echo "<script type='text/javascript'>alert('$success');</script>";
echo "<script> location.href='../main.php'; </script>";
}
} fclose($file);
} else {
$errorfile = "Operasi import gagal!";
echo "<script type='text/javascript'>alert('$errorfile');</script>";
echo "<script> location.href='../main.php'; </script>";
}

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

You have an error in your SQL syntax error message when inserting record

I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";

Uploading Csv Not Working after Modification

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

Categories