Home > Blockchain >  WordPress Plugin - unable to import csv data to custom plugin table
WordPress Plugin - unable to import csv data to custom plugin table

Time:10-18

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.

CodePudding user response:

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.

  • Related