Importing CSV to Database in WordPress - php

In the following code i try to import from CSV to Database in WordPress.
The data is inserted but I get this error
WordPress database error: []
INSERT INTO wp_trav_accommodation_vacancies (date_from, date_to, accommodation_id, room_type_id, rooms, price_per_room, price_per_person) VALUES ('2017-08-30', '2017-09-10', '1', '1', '3', '600.00', '0.00')
This is the code I run:
global $wpdb;
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false) {
$date_from = $filesop[0];
$date_to = $filesop[1];
$accommodation_id = $filesop[2];
$room_type_id = $filesop[3];
$rooms = $filesop[4];
$price_per_room = $filesop[5];
$price_per_person = $filesop[6];
$sql = "INSERT INTO wp_trav_accommodation_vacancies (date_from, date_to, accommodation_id, room_type_id, rooms, price_per_room, price_per_person) VALUES ('$date_from', '$date_to', '$accommodation_id', '$room_type_id', '$rooms', '$price_per_room', '$price_per_person')";
if ($wpdb->query($sql) === TRUE) {
echo "You database has imported successfully";
} else {
echo $wpdb->print_error();
my_print_error();
}
}
}
Can anyone tell what is wrong?

Related

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

Upload CSV file into SQL database

I am curently trying to upload a CSV file into a sql table, but I don't want to upload the first line which contains the name of every column value that will be inserted. I used a variable c to count the number of rows that will be inserted. For the first line c=0 so I used a condition to upload the values from the row only if c!==0, but it stil uploades the values from the first line.
My code looks like this:
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
if ($_FILES["file"]["type"]=='application/vnd.ms-excel')
{
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$qry = mysql_query("SELECT id FROM beneficiari WHERE `nume` = '".$beneficiar."'");
while ($row = mysql_fetch_assoc($qry)){
$id_client=$row['id'];
}
$qry_id_model=mysqli_query("SELECT id FROM modele WHERE `model` = '".$model."'");
while ($row = mysql_fetch_assoc($qry_id_model)){
$id_model=$row['id'];
}
$adresa1 = $adresa.",".$localitate;
if ($c!==0){
$sql = mysql_query(
"INSERT INTO pos_equipments_other
(id_client, model, tid, beneficiar, adresa, agentie, judet)
VALUES
('$id_client','$id_model','$tid','$beneficiar','$adresa1',
'$locatie','$judet')"
);
}
$c = $c + 1;
}
}

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

How to remove duplicate row records when importing CSV files to mysql using php?

I need to remove duplicate records when importing my current CSV files into the database. My files has been successfully updated, but when I tried to upload the same files again, it straight away inserted into it again. is there any way of I can remove duplicate records if i am importing the files?
<?
if(isset($_POST["submit"])){
$file = $_FILES['file']['tmp_name'];
//echo 'upload file name: '.$file.' ';
$handle = fopen($file, "r");
$c = 0;
$count =0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$count ++;
$ID = $filesop[0];
$Name = $filesop[1];
$Contact = $filesop[2];
$Email =$filesop[3];
if($count>1){
$sql = "INSERT INTO clients(id,name,contact,email,)VALUES($ID,'$Name',$Contact,'$Email',')";
$resultsql = mysqli_query($link, $sql);
//echo $resultsql; //how am i going to remove duplicates when if there is a duplicate record ?
1) Before inserting, check existing data.
<?php
if(isset($_POST["submit"])){
$file = $_FILES['file']['tmp_name'];
//echo 'upload file name: '.$file.' ';
$handle = fopen($file, "r");
$c = 0;
$count =0;
while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
{
$count ++;
$ID = $filesop[0];
$Name = $filesop[1];
$Contact = $filesop[2];
$Email =$filesop[3];
$checkExistingData = "SELECT * FROM clients WHERE name='$Name' AND contact='$Contact' AND email='$Email'";
$resultcheckExistingData = mysqli_query($link, $checkExistingData);
$countExistingData = mysqli_num_rows($resultcheckExistingData);
if($countExistingData == 0)
{
if($count>1) {
$sql = "INSERT INTO clients(id,name,contact,email,)VALUES($ID,'$Name',$Contact,'$Email',')";
$resultsql = mysqli_query($link, $sql);
//echo $resultsql; //how am i going to remove duplicates when if there is a duplicate record ?
.
.
}
.
.
}?>
2) If data got inserted and you want to delete duplicate rows from table. You can try this too.
DELETE c1 FROM clients c1, clients c2 WHERE c1.name = c2.name AND c1.contact = c2.contact AND c1.email = c2.email AND c1.id > c2.id;
Add unique key to one or more of your columns, column with unique key will store unique values only, duplicate values will not be inserted.

Import CSV file with a column having date or text inside

I have a CSV file with a column having a date in format d/m/Y or the word "Illimité" inside meaning unlimited in French.
I would like each time it reads "Illimité" it puts NULL value inside MySQL table.
Here is my current PHP code :
if (isset($_POST['submit'])) {
$query = "TRUNCATE TABLE `formation` ";
$result = mysql_query($query);
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while (($fileop = fgetcsv($handle, 1000, ";")) !== false) {
$nom = $fileop[0];
$prenom = $fileop[1];
$formation = $fileop[16];
$validite = $fileop[26];
if (is_numeric($validite)) {
$validite = date_format(date_create_from_format('d/m/Y', $validite), 'Y-m-d');
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation','$validite','importCSV')");
} else {
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation',NULL,'importCSV')");
}
}
Sadly this isn't working. MySql shows no errors and it puts NULL all the time.
Any help would me much appreciate.
Try this:
function myFunc($CSVValue){
if(validateDate($CSVValue)){
//your mysql logic where you put in the date
}else{
//your mysql logic where you put in the null
}
}
function validateDate($date)
{
$d = DateTime::createFromFormat('d/m/Y', $date);
return $d && $d->format('d/m/Y') == $date;
}
function was copied from this answer or php.net
-- update --
I don't know how your code looks other than what you have provided.
If you were to put this in your code it could look something like this:
if (isset($_POST['submit'])) {
$query = "TRUNCATE TABLE `formation` ";
$result = mysql_query($query);
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while (($fileop = fgetcsv($handle, 1000, ";")) !== false) {
$nom = $fileop[0];
$prenom = $fileop[1];
$formation = $fileop[16];
$validite = $fileop[26];
$d = DateTime::createFromFormat('d/m/Y', $validite);
if ($d && $d->format('d/m/Y') == $validite) {
$validite = date_format(date_create_from_format('d/m/Y', $validite), 'Y-m-d');
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation','$validite','importCSV')");
} else {
$sql = mysql_query("INSERT INTO formation (nom,prenom,formation,validite,usermaj) VALUES ('$nom','$prenom','$formation',NULL,'importCSV')");
}
}

Categories