incomplete insertion from csv to mysql database php - php

I am facing an error while inserting data records from CSV file to mysql database. I have a script which works fine. It inserts data from CSV file to mysql database. It has around 40,000 records. But after running the script, it inserts only around 1000 records and stops without error. What may be the problem? Please help.
Below is my script for inserting data.
include('dbconnection.php');
if (($handle = fopen("hotels.csv", "r")) !== FALSE) {
$flag = true;
$id=1;
while (($data = fgetcsv($handle, 100000000, ",")) !== FALSE) {
if($flag){
$flag = false;
continue;
}
$hotelid = mysql_real_escape_string($data[0]); //var_dump($hotelid); exit();
$hotelname = mysql_real_escape_string($data[1]);
$address1 = mysql_real_escape_string($data[2]);
$address2 = mysql_real_escape_string($data[3]);
$country = mysql_real_escape_string($data[4]);
$city = mysql_real_escape_string($data[5]);
$postcode = mysql_real_escape_string($data[6]);
$telephone = mysql_real_escape_string($data[7]);
$hotelfax = mysql_real_escape_string($data[8]);
$hotelemail = mysql_real_escape_string($data[9]);
$longitude = mysql_real_escape_string($data[10]);
$latitude = mysql_real_escape_string($data[11]);
$website = mysql_real_escape_string($data[12]);
$location = mysql_real_escape_string($data[13]);
$description = mysql_real_escape_string($data[14]);
$starrating = mysql_real_escape_string($data[15]);
$statecode = mysql_real_escape_string($data[16]);
$select_query = "SELECT * FROM `hotelDB`.`hotels` WHERE `hotelid` = $hotelid";
if(mysql_query($select_query) != '$hotelid'){
$sql = "INSERT IGNORE INTO `hotelDB`.`hotels` (`id`,`hotelid`, `hotelname`, `address1`,`address2`,`country`,`city`,`postcode`,`telephone`,`hotelfax`,`hotelemail`,`longitude`,`latitude`,`website`,`location`,`description`,`starrating`,`statecode`) VALUES ('$id','$hotelid', '$hotelname', '$address1','$address2', '$country', '$city', '$postcode', '$telephone', '$hotelfax', '$hotelemail', '$longitude', '$latitude', '$website', '$location', '$description', '$starrating', '$statecode')";
echo $sql;
$retval = mysql_query($sql,$conn);
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "<p style='color: green;'>Entered data having id = " .$id. " successfully</p><br>";
$id++;
}
}
echo "<br><p style='color: orange;'>Congratulation all data successfully inserted</p>";
fclose($handle);
}
mysql_close($conn);`
The insertion stops after inserting some values. This is example screenshot where the code stops executes.

You can try one query with multiple-row INSERT. In below example I am inserting 500 row with one insert query. You can change it to 1000.
<?php
include('dbconnection.php');
if (($handle = fopen("grnconnect-dump-hotels.csv", "r")) !== FALSE) {
//var_dump( $handle);
$flag = true;
$id=1;
$counter=0;
$sql = "INSERT IGNORE INTO `hotelDB`.`hotels` (`id`,`hotelid`, `hotelname`, `address1`,`address2`,`country`,`city`,`postcode`,`telephone`,`hotelfax`,`hotelemail`,`longitude`,`latitude`,`website`,`location`,`description`,`starrating`,`statecode`) VALUES";
$saveString="";
while (($data = fgetcsv($handle, 100000000, ",")) !== FALSE) {
//var_dump($data); exit();
if($flag){
$flag = false;
continue;
}
$hotelid = mysql_real_escape_string($data[0]); //var_dump($hotelid); exit();
$hotelname = mysql_real_escape_string($data[1]);
$address1 = mysql_real_escape_string($data[2]);
$address2 = mysql_real_escape_string($data[3]);
$country = mysql_real_escape_string($data[4]);
$city = mysql_real_escape_string($data[5]);
$postcode = mysql_real_escape_string($data[6]);
$telephone = mysql_real_escape_string($data[7]);
$hotelfax = mysql_real_escape_string($data[8]);
$hotelemail = mysql_real_escape_string($data[9]);
$longitude = mysql_real_escape_string($data[10]);
$latitude = mysql_real_escape_string($data[11]);
$website = mysql_real_escape_string($data[12]);
$location = mysql_real_escape_string($data[13]);
$description = mysql_real_escape_string($data[14]);
$starrating = mysql_real_escape_string($data[15]);
$statecode = mysql_real_escape_string($data[16]);
if(trim($counter)=="500") {
$sql = $sql.''.rtrim($saveString,",");
echo $sql;echo "<br /";
mysql_query($sql);
$counter=0;
$saveString="";
}
$saveString .="('".$id."','".$hotelid."', '".$hotelname."', '".$address1."','".$address2."', '".$country."', '".$city."', '".$postcode."', '".$telephone."', '".$hotelfax."', '".$hotelemail."', '".$longitude."', '".$latitude."', '".$website."', '".$location."', '".$description."', '".$starrating."', '".$statecode."'),";
$counter++;
}
if(trim($saveString)!=='') {
$sql = $sql.''.rtrim($saveString,",");
echo $sql;echo "<br /";
mysql_query($sql);
}
echo "<br><p style='color: orange;'>Congratulation all data successfully inserted</p>";
fclose($handle);
}
mysql_close($conn);
?>

Is there a particular reason to insert via script ?
Else I'd suggest you just insert manually or let the DB do it, sinces it's more efficient anyway. MySQL provides functions
for this: http://www.mysqltutorial.org/import-csv-file-mysql-table/

Related

Insert values from excel in mysql WordPress Php

i have this php code that is suppose to insert data from excel file to mysql database, from wordpress. This is the code:
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'excelvalues';
echo $table_name;
if(isset($_POST["submit_file"]))
{
$file = "example.csv"//$_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
{
$Anrede = $csv[0];
$Titel = $csv[1];
$Nachname = $csv[2];
$Vorname = $csv[3];
$Strasse = $csv[4];
$LKZ = $csv[5];
$PLZ = $csv[6];
$Ort = $csv[7];
$Mobil = $csv[8];
$Email = $csv[9];
$Geburtsdatum = $csv[10];
$Eintrittsdatum = $csv[11];
$Prüfungsjahr = $csv[12];
$Vermittlung = $csv[13];
$Bezirk = $csv[14];
$Kartennummer = $csv[15];
$LinkQR = $csv[16];
$wpdb->query("INSERT INTO $table_name(ID, Anrede, Titel,Nachname,Vorname,Strasse,LKZ,PLZ,Ort,Mobil,Email,Geburtsdatum,Eintrittsdatum,Prüfungsjahr,Vermittlung,Bezirk,Kartennummer,LinkQR) VALUES(NULL, '$Anrede', '$Titel', '$Nachname', '$Vorname', '$Strasse', '$LKZ', '$PLZ', '$Ort', '$Mobil', '$Email', '$Geburtsdatum', '$Eintrittsdatum', '$Prüfungsjahr', '$Vermittlung', '$Bezirk', '$Kartennummer', '$LinkQR')");
}
}
?>
The code works it inserts values on the database but the values are only the number of rows from excel but the values are missing, i dont understand what am i doing wrong.
Currently you retrieved the row id to each variable. This should work -
global $wpdb;
$table_name = $wpdb->prefix . 'excelvalues';
if(isset($_POST["submit_file"])){
$csvFile = file( 'example.csv' );
$all_data = [];
// fetch all data to array
foreach( $csvFile as $line ){
$all_data[] = str_getcsv( $line );
}
// fetch data from each row
foreach( $all_data as $row_key => $rows ){
// fetch data from each column
$Anrede = $rows[0];
$Titel = $rows[1];
$Nachname = $rows[2];
$Vorname = $rows[3];
$Strasse = $rows[4];
$LKZ = $rows[5];
$PLZ = $rows[6];
$Ort = $rows[7];
$Mobil = $rows[8];
$Email = $rows[9];
$Geburtsdatum = $rows[10];
$Eintrittsdatum = $rows[11];
$Prüfungsjahr = $rows[12];
$Vermittlung = $rows[13];
$Bezirk = $rows[14];
$Kartennummer = $rows[15];
$LinkQR = $rows[16];
// Insert into table
$wpdb->query("INSERT INTO $table_name(ID, Anrede, Titel,Nachname,Vorname,Strasse,LKZ,PLZ,Ort,Mobil,Email,Geburtsdatum,Eintrittsdatum,Prüfungsjahr,Vermittlung,Bezirk,Kartennummer,LinkQR) VALUES(NULL, '$Anrede', '$Titel', '$Nachname', '$Vorname', '$Strasse', '$LKZ', '$PLZ', '$Ort', '$Mobil', '$Email', '$Geburtsdatum', '$Eintrittsdatum', '$Prüfungsjahr', '$Vermittlung', '$Bezirk', '$Kartennummer', '$LinkQR')");
}
}

importing the excel data into database table using php

problem is in my excel 369 rows are there. when I echo/print that data it showing correct but when I am inserting same data in DB table in inserted only 18 - 30 records.
if (isset($_POST['Submit'])) {
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
if ($file == NULL) {
error(_('Please select a file to import'));
redirect(page_link_to('excel_data_upload'));
}else {
$conn = connect();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$num3 = $filesop[3];
$num8 = $filesop[8];
$num9 = $filesop[9];
$num20 = $filesop[20];
if($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO'){
$insertAgent = mysqli_query($conn, "INSERT INTO `upload_billing_data`
(`vc_number`,`stb_number`,`operator_id`,`expiry_date`,`monthly_bill_amount`)
VALUES ('$num8','$num9',140,'$num3','$num20')");
if($insertAgent)
{
echo 'succss';
}else{
echo 'error';
}
}
}
close($conn);
}
}
I am fetching from the excel data. I want to insert all records
Change the code as below and you might get to save all data using one query to the database:
$query_insert = array();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) {
$num3 = filterString($filesop[3]);
$num8 = filterString($filesop[8]);
$num9 = filterString($filesop[9]);
$num20 = filterString($filesop[20]);
if ($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO') {
$query_insert[] = "('{$num8}', '{$num9}', 140, '{$num3}', '{$num20}')";
}
}
// If no row matched your if, then there will be no row to add to the database
if (count($query_insert)>0) {
$conn = connect();
$query_insert_string = implode(', ', $query_insert);
$query = "INSERT INTO `upload_billing_data` (`vc_number`, `stb_number`, `operator_id`, `expiry_date`, `monthly_bill_amount`) VALUES {$query_insert_string};";
$insertAgent = mysqli_query($query);
// The rest of you code
...
close($conn);
}
// This function makes sure that you string doesn't contain characters that might damage the query
function filterString($string) {
$string = str_replace(array("\'", '"'), array('', ''), $string);
$string = filter_var($string, FILTER_SANITIZE_STRING);
return $string;
}
Please check this modified code
if (isset($_POST['Submit'])) {
$file = $_FILES['csv_file']['tmp_name'];
$handle = fopen($file, "r");
if ($file == NULL) {
error(_('Please select a file to import'));
redirect(page_link_to('excel_data_upload'));
}else {
$conn = connect();
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$num3 = $filesop[3];
$num8 = $filesop[8];
$num9 = $filesop[9];
$num20 = $filesop[20];
if($num3!='ExpiryDate' &&$num8!='VCNO' &&$num20!='TotalB2CAmount' && $num9 !='STBNO'){
$insertAgent = mysqli_query($conn, "INSERT INTO `upload_billing_data`
(`vc_number`,`stb_number`,`operator_id`,`expiry_date`,`monthly_bill_amount`)
VALUES ('".mysqli_real_escape_string($num8)."','".mysqli_real_escape_string($num9)."',140,'".mysqli_real_escape_string($num3)."','".mysqli_real_escape_string($num20)."')");
if($insertAgent)
{
echo 'succss';
}else{
echo 'error';
}
}
}
close($conn);
}
}
BY using mysqli_real_escape_string() you will be able to avoid sqlinjection issues and you will be able to handle issue of quotes which might be causing an issue.
in your else block where you are echo "error". you can use mysqli_error($conn); to get exact what error is occurring while performing an insert

How to check for duplicate values for excel sheet values before storing in database

I'm getting data from excel sheet and storing it in database. It is storing the data successfully. I had created two tables in database, one is to import values from excel sheet & store temporarily and other is to get values from temporarily stored table,also checking for duplicate records.
I can insert data in second table but please suggest me how to check duplicate records before storing in original table.
This is the code:
<?php
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$row = 1;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$row++;
if($row != 1)
{
$custid = $filesop[0];
$zone = $filesop[1];
$city = $filesop[2];
$category = $filesop[3];
$focus = $filesop[4];
$customer_type = $filesop[5];
$lead_source = $filesop[6];
$exhibition = $filesop[7];
$organization_name = $filesop[8];
$assign_to = $filesop[9];
$description = $filesop[10];
$division = $filesop[11];
$product = $filesop[12];
$grade = $filesop[13];
$potential = $filesop[14];
$firstname = $filesop[15];
$lastname = $filesop[16];
$designation = $filesop[17];
$mobile = $filesop[18];
$primary_phone = $filesop[19];
$primary_email = $filesop[20];
$address_type = $filesop[21];
$address1 = $filesop[22];
$address2 = $filesop[23];
$state = $filesop[24];
$country = $filesop[25];
$hgf = "INSERT INTO temp_const set custid='$name', zone='$zone', city='$city', category='$category', focus='$focus', customer_type='$customer_type', lead_source='$lead_source', exhibition='$exhibition', organization_name='$organization_name', assign_to='$assign_to', description='$description', division='$division', product='$product', grade='$grade', potential='$potential', firstname='$firstname', lastname='$lastname', designation='$designation', mobile='$mobile', primary_phone='$primary_phone', primary_email='$primary_email', address_type='$address_type', address1='$address1', address2='$address2', state='$state', country='$country' ";
$sql = mysql_query($hgf);
$c = $c + 1;
}
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ."recoreds";
}else{
echo " Sorry! There is some problem.";
}
}
?>
You can create a unique index on the fields where you want to check on duplication, lets say it is fieldA, fieldB and fieldC
ALTER TABLE destTable add unique key idx_abc (fieldA,fieldB,fieldC);
after this you can copy your tmp table into the destTable with the option IGNORE
INSERT IGNORE INTO destTable SELECT * FROM temp_const;
or use only the field you want.

php getting data from excel sheet to mysql(how to avoid first row?)

i am getting data from excel sheet and storing it in database it is storing the data successfully but i dont want store the first row of the table which is the header. help me out to get it done.
this is the code:
<?php
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$row = 1;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$custid = $filesop[0];
$zone = $filesop[1];
$city = $filesop[2];
$category = $filesop[3];
$focus = $filesop[4];
$customer_type = $filesop[5];
$lead_source = $filesop[6];
$exhibition = $filesop[7];
$organization_name = $filesop[8];
$assign_to = $filesop[9];
$description = $filesop[10];
$division = $filesop[11];
$product = $filesop[12];
$grade = $filesop[13];
$potential = $filesop[14];
$firstname = $filesop[15];
$lastname = $filesop[16];
$designation = $filesop[17];
$mobile = $filesop[18];
$primary_phone = $filesop[19];
$primary_email = $filesop[20];
$address_type = $filesop[21];
$address1 = $filesop[22];
$address2 = $filesop[23];
$state = $filesop[24];
$country = $filesop[25];
$hgf = "INSERT INTO temp_const set custid='$name', zone='$zone', city='$city', category='$category', focus='$focus', customer_type='$customer_type', lead_source='$lead_source', exhibition='$exhibition', organization_name='$organization_name', assign_to='$assign_to', description='$description', division='$division', product='$product', grade='$grade', potential='$potential', firstname='$firstname', lastname='$lastname', designation='$designation', mobile='$mobile', primary_phone='$primary_phone', primary_email='$primary_email', address_type='$address_type', address1='$address1', address2='$address2', state='$state', country='$country' ";
$sql = mysql_query($hgf);
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ."recoreds";
}else{
echo " Sorry! There is some problem.";
}
}
?>
$flag = true;
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
if($flag) { $flag = false; continue; }
//your code
i hope it will be helpful

cannot update the database

i want to update my data from database but unfortunately i can't be update.
there is anyone can help me.
i will be appreciated.
the problem is error can not show when my code does wrong.
sorry for my bad english.
here is my code
<?
include "new.php";
$response = array("updated data", 1);
if (isset($_POST['ID_Person']) && isset($_POST['FirstName']) && isset($_POST['MiddleName']) && isset($_POST['LastName']) && isset($_POST['AliasName'])
&& isset($_POST['Gender']) && isset($_POST['CityBirth']) && isset($_POST['DateBirth']) && isset($_POST['MonthBirth']) && isset($_POST['YearBirth']))
{
$id = $_POST['ID_Person'];
$name = $_POST['FirstName'];
$middle = $_POST['MiddleName'];
$last = $_POST['LastName'];
$alias = $_POST['AliasName'];
$gender = $_POST['Gender'];
$citybirth = $_POST['CityBirth'];
$datebirth = $_POST['DateBirth'];
$monthbirth = $_POST['MonthBirth'];
$yearbirth = $_POST['YearBirth'];
$hasil = sqlsrv_query($conn,"UPDATE T_Person SET
First_Name_Person = '$name' ,
Middle_Name_Person = '$middle' ,
Last_Name_Person = '$last' ,
Alias_Person = '$alias',
Gender_Person = '$gender',
City_Birth_Person = '$citybirth',
Date_Birth_Person = '$datebirth',
Month_Birth_Person = '$monthbirth',
Year_Birth_Person = '$yearbirth',
WHERE ID_Person = '$id'"
);
$rows_affected = sqlsrv_rows_affected($hasil);
if ($rows_affected === false)
{
die( print_r( sqlsrv_errors(), true));
}
if ($hasil)
{
$response["success"] = 1;
$response["message"] = "Product successfully edit.";
// echoing JSON response
echo json_encode($response);
}
}
else {
echo 'Data fail update';
}
?>
You have an error in your query with comma juste before WHERE
$hasil = sqlsrv_query($conn,"UPDATE T_Person SET First_Name_Person = '$name' ,
Middle_Name_Person = '$middle' ,
Last_Name_Person = '$last' ,
Alias_Person = '$alias',
Gender_Person = '$gender',
City_Birth_Person = '$citybirth',
Date_Birth_Person = '$datebirth',
Month_Birth_Person = '$monthbirth',
Year_Birth_Person = '$yearbirth',
no comma here ^
WHERE ID_Person = '$id'");
Try to echo your query in the PHP and copy paste this query in phpMyAdmin.
i guess there is no T_Person with ID_Person == $id in your table so nothing is updated
Please remove comma after this,
Year_Birth_Person = '$yearbirth'

Categories