avoiding added data when importing csv file into mysql - php

Okay, I'm having some serious issues here. I'm new to this site, and new to dealing with importing CSV data via PHP, and also I'm newbies in programming.
when i importing csv file into mysql there is some added data on my database filed
here is my script to upload csf file into mysql
<?php
include '../php/koneksi.php';
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($Data = fgetcsv($file, 1000, ",")) !== FALSE)
{
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into raport (`no_induk`, `nama`, `kelas`, `jurusan`,mapel, `semester`, `nilai`, `deskripsi`)
values(
'".trim($Data[0], '"')."',
'".trim($Data[1], '"')."',
'".trim($Data[2], '"')."',
'".trim($Data[3], '"')."',
'".trim($Data[4], '"')."',
'".trim($Data[5], '"')."',
'".trim($Data[6], '"')."',
'".trim($Data[7], '"')."'
)";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql);
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"upload.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"upload.php\"
</script>";
//close of connection
mysql_close;
}
}
?>

Related

Import certain csv/excel data to mysql database using PHP

Is there any way to select a certain csv/excel cells then import its data to database? I have a similar program but it only import the first, second, etc. columns.
So here's the php codes for reading excel data and input.
<?php
include 'db.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)
{
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into subject (`SUBJ_CODE`, `SUBJ_DESCRIPTION`, `UNIT`, `PRE_REQUISITE`,COURSE_ID, `AY`, `SEMESTER`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysqli_query( $conn, $sql );
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
//close of connection
mysqli_close($conn);
}
}
?>
It only import the selected columns
Example
Excel
What I want is to find a certain cell by reading the cell data and import the data below it. Here's visualization:
What I want to do:
Is there any way to do this? I need help. Thank you
Here is the sample program:
https://www.sourcecodester.com/tutorials/php/6989/how-import-excelcsv-file-mysql-database-using-php.html
If you want to do it for just once than you can use some online tools.
If you want to have a code for this than you can do by following code
$open = fopen("filename.csv", "r"); // This will open the file for you
$data = fgetcsv($Open, 1000, ","); // Read Line be Line
while (($data = fgetcsv($Open, 1000, ",")) !== FALSE)
{
// Read the data
}

cannot upload csv file and get error C:\xampp\tmp\php9F4F.tmp

I'm working on a website that required me to create function to upload .csv file.
When upload the file, it says wrong format, and it display this message:
C:\xampp\tmp\php9F4F.tmp
p/s:I already convert the excel file into .csv comma delimited format and still get error while uploading.
What should I do to resolve the error and then get to upload the csv file into my database?
stdreport.php : //im using the same code from import.php in here to connect it with database
<?php
$SQLSELECT = "SELECT stdCard, stdName, stdProgram, stdCourseDesc, stdCampus
FROM student
ORDER BY stdID
LIMIT 0,20";
$result_set = mysql_query($SQLSELECT, $conn);
while($row = mysql_fetch_array($result_set))
{
?>
import.php
<?php
$conn=mysql_connect("localhost","root","") or die("Could not connect");
mysql_select_db("dashboard",$conn) or die("could not connect database");
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) {
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into student
(`stdID`, `stdCard`, `stdName`,
`stdOfficialEmail`,`stdEmail`,
`stdContNum`,`stdCourseDesc`, `stdCampus`,
`accessDate`)
values('$emapData[1]','$emapData[2]','$emapData[3]',
'$emapData[4]','$emapData[5]',
'$emapData[6]', '$emapData[7]','$emapData[8]',
'$emapData[9]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(! $result ) {
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"stdreport.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"stdreport.php\"
</script>";
//close of connection
mysql_close($conn);
}
}
?>
When you convert the excel file to CSV then there is two type of formate CSV UTF-8 (comma delimited ) and the second one is CSV (comma delimited ), use the second option I have also attached the screenshot.

Data incomplete -- Importing CSV-files into a PostgreSQL database using PHP

I have a problem importing csv-files into a PostgreSQL database using php. The csv-file holds around 11000 datalines, however php only imports around 2100 lines. (I looked through the data and found special characters like
<!--. I replaced them with "nan" but the problem remains.)
When I import it with the pgAdmin wizard it works fine and imports the data completely (even with the special characters left in).
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
ini_set("auto_detect_line_endings", true);
$file = fopen($filename, "r");
$flag = true;
$row = 1;
while (($getData = fgetcsv($file, 10000, ";")) !== FALSE)
{
if($flag) { $flag = false; continue; }
$sql = "INSERT into public.fulldict (studiennr,studienname,formular,formularmodul,modul_id,titel_der_ableitung,abl_version,feldname,hilfetext,variablenname,pflichtfeld,feldtyp,feldlaenge,min_wert,max_wert,einheit,code,read_only,exeptional_values,passiv)
values ('".pg_escape_string($getData[0])."','".pg_escape_string(($getData[1]))."','".pg_escape_string(($getData[2]))."','".pg_escape_string(($getData[3]))."','".pg_escape_string(($getData[4]))."','".pg_escape_string(($getData[5]))."','".pg_escape_string(($getData[6]))."','".pg_escape_string(($getData[7]))."','".pg_escape_string(($getData[8]))."','".pg_escape_string(($getData[9]))."','".pg_escape_string(($getData[10]))."','".pg_escape_string(($getData[11]))."','".pg_escape_string(($getData[12]))."','".pg_escape_string(($getData[13]))."','".pg_escape_string(($getData[14]))."','".pg_escape_string(($getData[15]))."','".pg_escape_string(($getData[16]))."','".pg_escape_string(($getData[17]))."','".pg_escape_string(($getData[18]))."','".pg_escape_string(($getData[19]))."')";
$result = $con -> prepare($sql);
$result -> execute();
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"upload.php\"
</script>";
}
else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"upload.php\"
</script>";
}
}
fclose($file);
ini_set("auto_detect_line_endings", false);
}
It works now. I had to move the if(!isset($result)){} outside of the loop. The check caused the loop to end prematurely. However I don't see how $resultcould be empty before the csv-file is read completely...

CSV upload not leaving header, show empty rows if any,match with mysql to prevent duplicate

I need to solve the following problems:
My script not leaving headers of CSV file.
Show error if empty field in CSV file.
Match with MySQL table to prevent duplicate.
<?php
include 'db.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)
{
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into old_plot_details (`mem_ship_no`, `mem_fname`, `venture_name`, `phase_name`,`plot_no`, `regd_name`, `doc_no`, `reg_date`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$emapData[7]','$emapData[8]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(!$result)
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
//close of connection
mysql_close($conn);
}
}
?>

Need help with updating a mysql table by a csv file upload

Following is my script to upload the table employee with a csv file. The file is uploading and upldating the employee table perfectly. BUT the problem is i specified a row with headings in the csv file. That heading row is also getting updated in the table. I want only those datas to get uploaded except the heading row in the csv file, any help or ideas?.
<?php
require_once '../config.php';
if(isset($_POST['upload']))
{
$fname = $_FILES['sel_file']['name'];
$chk_file = explode(".",$fname);
if(strtolower($chk_file[1]) == 'csv')
{
$filename = $_FILES['sel_file']['tmp_name'];
$handle = fopen($filename,"r");
while(($data = fgetcsv($handle,1000,",")) != false)
{
$sql = "INSERT into employee(employee_code,employee_name,employee_address,emp_dateofjoin,emp_designation,emp_hq,pf_num,esic_num,emp_state,month,tot_work_days,lop_days,arrear_amt,leave_encash) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]')";
/$upd = "UPDATE student SET month='',tot_work_days='',lop_days='',arrear_amt='',leave_encash='' where employee_code=''";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully Imported";
}
else
{
echo "Invalid File";
}
}
?>
Skip the first line by calling fgetcsv once before your loop:
fgetcsv($handle,1000,",");
while(($data = fgetcsv($handle,1000,",")) != false)
You also could use LOAD DATA INFILE MySQL statement with 'IGNORE 1 LINES' clause.

Categories