php - 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!
解决方案
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!
推荐阅读
- python-3.x - 如何在 python 中播放实时音频,同时不断录制?
- android - 在 Jenkins 的 Docker 容器中编译 Android 项目
- matlab - 具有 theta、phi 和半径的 Polar(3D) 图
- javascript - 除大数时,有没有办法获得更精确的结果?
- excel - 是否有像 IsNumeric 这样的 VBA 函数,但用于文本?当涉及范围时,IsText 和 IsEmpty 的工作方式不同
- amazon-web-services - Terraform 与 API-Gateway、Route53 和 SSL 认证相互依赖问题
- php - Docker php-fpm + nginx / 有时在 php 文件中找不到文件
- php - php 相当于 window.location.replace()
- node.js - 卸载可选依赖项缺少依赖项的 NPM 列表错误
- c++ - 未定义的行为会影响 static_assert 吗?