首页 > 解决方案 > Laravel-Eloquent-Adding record to MySQL: Building dynamic eloquent insert command, and it returns "Column Not Found" on the very first column

问题描述

I've rewritten this help request, and simplified what I'm attempting to minimize the number of moving parts.

I'm an experience OOP programmer, but this is my first project with LAMP, Laravel, or Eloquent.

I'm building a data import facility in Laravel-Spark. User will provide a .csv file. My program will determine what data has been provided based on the header (first) row of data. From there it will insert a new row into a MySQL table and update the provided fields.

function ImportPositions($incomingfile)
  {
    if (($handle = fopen ( public_path () . '/ImportFiles/samplepositions.csv', 'r' )) !== FALSE) {

        $header = fgetcsv($handle, 2000, ',');
        $headercount = count($header);

        while ( ($data = fgetcsv ( $handle, 2000, ',' )) !== FALSE ) {

          $position = new Position;
          $i = 0;
          while ($i<$headercount):

              $fieldname=$header[$i];
              $fielddata=$data[$i];
              // Example:  $position->posno="12345";
              $position->$fieldname=$fielddata;

              $i++;
          endwhile;

          $position->save();
      }
        fclose ( $handle );
    }
  }

The code returns this error. The field definitely exists.

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'active' in 'field list' (SQL: insert into `positions` (`active`, `updated_at`, `created_at`) values (A, 2019-11-12 03:32:50, 2019-11-12 03:32:50))

In an attempt to debug, this works fine:

$fieldname2='active';
$fielddata2='A';
$position->$fieldname2=$fielddata2; 
$position->save();

Next, try to prove that my derived values are valid:

$fieldname=$header[$i];
$fielddata=$data[$i];

$fieldname2='active';
$fielddata2='A';

dump("|".$fieldname."|".$fieldname2."|");
dd("|".$fielddata."|".$fielddata2."|");

returns the following, so the two sets of variables appear to be identical:

"|active|active|"
"|A|A|"

BUT: when I substitute the derived variables for the typed variables, it fails and gives the error listed above.

$fieldname=$header[$i];
$fielddata=$data[$i];
$position->$fieldname=$fielddata;
$position->save();

Thanks for any help!

标签: phpmysqllaraveleloquent

解决方案


Answer: My input file had a BOM marker, which caused a problem with the import. It was messing up the SQL statement, even though it wasn't visible in the debugging messages that showed the script.

TO FIX: Easy: Open the import file in Notepad++, and check "ENCODING." My file showed "UTF-8-BOM." I changed it to "UTF-8" and fixed the problem.

Thanks to everyone that gave input!


推荐阅读