PHP | Upload Excel into SQL Databse - Getting Error Undefined Offset - php

Okay, I am getting a Undefiend Offset Error on [1] and [2] which should be $Event_Date and $Event_Organization.
The weird thing is that I also have it set to display the row and the data entered for said row. It even displays this data correctly via echo.
Another strange thing is I have a second CSV upload area on the site that is a carbon copy that work correctly. The only differance is the $_GET ($Type) for the url passed Variable.
Maybe I should change it to a $_POST instead? They only thing $Type does is determine if it is a Bulk Entry or Single Entry.
Edit 1
I changed it from a $_GET to a $_POST by adding a hidden field in the form on the prior page, and still received the same error.
$Type = $_GET["Type"];
if($Type == 'Bulk')
{
if ($_FILES['Excel']['size'] > 0)
{
//get the csv file
$file = $_FILES['Excel']['tmp_name'];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
$column_headers = array();
$row_count = 0;
$Count = 1;
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE)
{
if ($row_count != 0)
{
//user input
$Event_Name = $data[0];
$Event_Date = $data[1];
$Event_Organization = $data[2];
echo ' '.$Event_Name.' '.$Event_Date.' '.$Event_Organization.'<br> <br>';
//Add Account Informaion | Login
$Create_Event_Query ='INSERT INTO Event(Event_Name,
Event_Date, Event_Organization)
VALUES(?,?,?)';
$Create_Event_stmt = $conn->prepare($Create_Event_Query);
$Create_Event_stmt->bind_param('sss',$Event_Name,$Event_Date,$Event_Organization);
$Create_Event_stmt->execute();
if(!$Create_Event_stmt)
{
Echo'<h2>Try Again</h2>';
}
else
{
echo'Enter Row: '.$row_count.'<br>';
echo ' '.$Event_Name.' '.$Event_Date.' '.$Event_Organization.'<br> <br>';
}
$Create_Event_stmt->close();
$row_count = $row_count + 1;
}
else
{
$column_headers = $data;
$row_count = $row_count + 1;
}
}
Echo'<h2>GO Back</h2>';
}
else
{
}
}

Related

WordPress Plugin - unable to import csv data to custom plugin table

i have a wordPress plugin, and i am unable to add the data to the custom db table. Here is what i have tried so far.
i have tried one row insert as well, nothing is getting inserted, what i am doing wrong here? thanks for taking your time to checking.
<?php
global $wpdb;
// Table name
$tablename = $wpdb->prefix."bohio";
// Import CSV
if(isset($_POST['butimport'])){
// File extension
$extension = pathinfo($_FILES['import_file']['name'], PATHINFO_EXTENSION);
// If file extension is 'csv'
if(!empty($_FILES['import_file']['name']) && $extension == 'csv'){
$totalInserted = 0;
// Open file in read mode
$csvFile = fopen($_FILES['import_file']['tmp_name'], 'r');
fgetcsv($csvFile); // Skipping header row
// Read file
while(($csvData = fgetcsv($csvFile)) !== FALSE){
$csvData = array_map("utf8_encode", $csvData);
// Row column length
$dataLen = count($csvData);
// Skip row if length != 4
if( !($dataLen == 4) ) continue;
// Assign value to variables
$square_feet = trim($csvData[0]);
$bed = trim($csvData[1]);
$bath = trim($csvData[2]);
$bh_service = trim($csvData[3]);
$price = trim($csvData[4]);
// Check record already exists or not
$cntSQL = "SELECT count(*) as count FROM {$tablename} where price='".$price."'";
$record = $wpdb->get_results($cntSQL, OBJECT);
if($record[0]->count==0){
// Check if variable is empty or not
if(!empty($square_feet) && !empty($bed) && !empty($bath) && !empty($bh_service) && !empty($price) ) {
// Insert Record
$wpdb->insert($tablename, array(
'square_feet' =>$square_feet,
'bed' =>$bed,
'bath' =>$bath,
'bh_service' =>$bh_service,
'price' => $price
));
if($wpdb->insert_id > 0){
$totalInserted++;
}
}
}
}
echo "<h3 class='bohio_valid'>Total record Inserted : ".$totalInserted."</h3>";
}else{
echo "<h3 class='bohio_invalid'>Invalid File Extension</h3>";
}
}
?>
CSV data i am importing from a file is here:
square_feet,bed,bath,bh_service,price
Under 1000,studio,1,Deep Clean,300.00
Under 1000,studio,1,Move In/Move Out,350.00
Under 1000,studio,1,Post Construction,375.00
1000-1600,1,1,Deep Clean,350.00
The data is not getting added at all.
Solved it.
I had actually 5 data columns and i was actually allowing only 4.
// Skip row if length != 4
if( !($dataLen == 4) ) continue
Changed it to 5, and it worked like a charm.

I'm trying to loop through a CSV file in PHP and add the returned data into a mysql db

Here is the PHP / xAjax function we are calling when we click a submit CSV button, I can get a response at the end of the function using a pop up modal that has the correct data but it doesn't get inserted into our database. I want to know why i can return data on the page but once I try to send it to mysql there is no response. There is also HTML code and Javascript involved but I believe there are no issues with those.
$fileHandle = fopen("test.csv", "r");
// Skips Headers in csv file
fgets($fileHandle);
//Loop through the CSV rows.
while (($row = fgetcsv($fileHandle, 10000, ",")) !== FALSE) {
//Print out my column data.
$orderFormData['testdata1'] = $row[0];
if(strlen($orderFormData['testdata1']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
$orderFormData['testdata2'] = $row[1];
if(strlen($orderFormData['testdata2']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
$orderFormData['testdata3'] = $row[2];
if(strlen($orderFormData['testdata3']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
$orderFormData['testdata4'] = $row[3];
if(strlen($orderFormData['testdata4']) == '' ){
$VerifyStatus = 'Missing data in CSV file, please take a look for empty cells.';
}
// Rob //
$orderFormData['Note'] = preg_replace('/[^\da-z \-,#$%&()_+=*#?.]/i', '', $orderFormData['Note']);
if(strlen($contactFormData['testdata5']) == '' ){
$VerifyStatus = 'Please enter a company contact so that we can get in touch if there are any issues with your order!';
}
$DebugText .= "<BR>".$VerifyStatus;
if ($VerifyStatus == 'OK') {
$query = "INSERT INTO testtable set ".
"Status = \"Open\", ".
"Source = \"testportal\", ".
"data1 = \"".$orderFormData['testdata1']."\",".
"data2 = \"".$orderFormData['testdata2']."\",".
"data3 = \"".$orderFormData['testdata3']."\",".
"RecordDate= \"".$q_time."\"";
$DebugText.= "<BR>".$query;
$result = mysqli_query($GLOBALS['link'], $query);
if (!$result){
$objResponse->addScript('swal("Oops...", "'.$VerifyStatus.'", "error");');
};
$rows_affected=mysql_affected_rows();
$DebugText.= "<BR>rows affected: ".$rows_affected;
if($rows_affected>0){
$objResponse->addScript('Swal("Order Recieved", "Check orders page for updates!");');
$objResponse->addScript('clearForms();');
}
} else{
$objResponse->addScript('swal("Oops...", "'.$VerifyStatus.'", "error");');
}
return $objResponse->getXML();
}
You never set $VerifyStatus to 'OK', it should be done just after the While starts then, if you find no errors that will set it to something else the database query will run
while (($row = fgetcsv($fileHandle, 10000, ",")) !== FALSE) {
$VerifyStatus = 'OK';

How to know csv cell location that have import problem in php?

I do an upload form for user to upload csv file. Data in csv will be imported to database. Data will be import to database if no error occur. But sometimes there is mismatch of data with column data type. Example column data type is "int", data in csv is "varchar". How can i know which cell have error and tell user?
Untill now, i just do an error message "There is format error in the csv file" if csv file unsuccessfully imported.
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){
$sql = "INSERT INTO Diary(id, date, remarks, status) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
if($sql==0){
echo " There is format error in the csv file ";
}
$res=$dbcon->query($sql);
}
fclose($file);
echo "CSV File has been succesfully Imported";
}
else
echo 'Invalid File:Please Upload CSV File';}
Why don't you validate values before insert values into database
if(is_numeric($emapData[0]) && is_numeric($emapData[1]) ....)
{
$sql = "INSERT INTO Plant_Diary(plant_core_id, date_diary, remarks, plant_status) VALUES('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
}
else{
echo 'error data type';
}
All you need to do is find the current row and column, and check data type of each column.
I prefer to create a function array to do check by column.
$checkColType = array(
#### col => function($val){ return 'error msg'; }
0 => function( $val ){
if( some statement ){ return 'Is not an id'; }
},
1 => function( $val ){
if( some statement ){ return 'Is not a date'; }
},
2 => etc...
);
$row = 0;
while(($emapData = fgetcsv($file, 10000, ",")) !== FALSE){
$CurrentRow = $row+1;
$ErrorMsg = '';
#### Do Check, and return Error
foreach( $checkColType as $col => $ColTypeFns ){
$CurrentCol = $col+1;
$Error = $ColTypeFns( $emapData[ $col ] );
if( $Error ){
$ErrorMsg.= "Cell $CurrentRow-$CurrentCol: $Error";
}
}
if( $ErrorMsg ){ echo "$ErrorMsg"; }
else{
#### Do Something...
}
$row++;
}

Lookup in CSV file is failing

I have a form where the user enters their first and last names. I want to check if their full name is present in my CSV file, which I use to store all current members / users of my form. The format in which data is stored is firstname,lastname. And if they are present, I want to print out You are already a member.
But that is not what I see in output, when I run my code. It doesn't output that, even if I input names which are present in the CSV file.
Here is my source code:
$JLMembers = Array();
// Open the file of Members
if ($handle = fopen("JLMembers.csv", "r")) {
// Get the next CSV line
while ($data = fgetcsv($handle, 1000, ",")) {
// Add that line to the array
array_push($JLMembers, $data);
}
}
foreach($JLMembers as $JLMember) {
$FirstName = $_GET['FirstName'];
$CurrentMemberFirstName = $JLMembers[0];
if ($FirstName === $CurrentMemberFirstName) {
foreach($JLMembers as $JLMember) {
$SecondName = $_GET['LastName'];
$CurrentMemberSecondName = $JLMembers[1];
if ($SecondName === $CurrentMemberSecondName) {
print "<br>You are already a member<br>";
}
}
}
}
You're using $JLMembers[0], which contains the first row of the CSV, when you should be using $JLMember[0], which contains the first column of the current row in the foreach loop. And you don't need two loops, just compare both columns in one loop.
The code should be:
$FirstName = $_GET['FirstName'];
$LastName = $_GET['LastName'];
foreach ($JLMembers as $JLMember) {
if ($FirstName == $JLMember[0] && $LastName == $JLMember[1]) {
echo "<br>You are a member<br>";
break; // Exit the loop once we found a match
}
}

Searching array for partial (or exact) match [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Closed 1 year ago.
I have some code that takes from a txt file a list of emails and inserts them into a database, making sure not to add the email if it's already in said database. What I'm trying to do now is filter emails as they are read from the txt file and NOT insert them if they are an exact or partial match to any strings within the $filter array. In other words, if the email has 'gmail', '.ru' or 'exec' anywhere within the email address, I don't want it added.
Any help to stop the bleeding from me pounding my head against a wall would be great!
The code:
$TheFile = "emails.txt";
$handle = fopen($TheFile, 'r');
$good_count = 0;
$bad_count = 0;
$filter= array("gmail",".ru","exec");
while (!feof($handle))
{
$Data = fgets($handle, 1024);
$output = explode (",",$Data);
$exist = mysql_query("SELECT * FROM table WHERE email='$output[0]'");
if (mysql_num_rows ($exist) == 0) {
$email = strtolower($output[0]);
$sql = "INSERT INTO table SET email='$email'";
mysql_query($sql);
$good_count = $good_count + 1;
}
else {
$bad_count = $bad_count + 1;
}
}
Use stripos in a validation function:
function validate_email($input, array $needles) {
foreach ($needles as $needle) {
if (stripos($input, $needle) === false) return false;
}
return true;
}
// ...
if (mysql_num_rows ($exist) == 0 &&
validate_email($output[0], $filter))
{
$email = strtolower($output[0]);
$sql = "INSERT INTO table SET email='$email'";
mysql_query($sql);
$good_count = $good_count + 1;
}
else {
$bad_count = $bad_count + 1;
}
Also, consider using a UNIQUE index in your table definition. This will cause a (catchable) MySQL error if the email already exists and will offload your script from doing a SELECT query for every email in your file.

Categories