在使用 csv 文件创建 table 到 mysql 时添加反引号 -PHP

Add backticks in creating table to mysql with csv file -PHP

我有一个 php 代码,它将使用 csv 文件创建一个 table 到 mysql 的数据库。但是,某些列 headers 未被 mysql 读取。 mysql 唯一一次读取查询是在我添加 反引号 (`) 时。你能帮我在查询中的什么地方放反引号吗? :(

这是我的代码:

   $file = 'C:\Users\user\Desktop\Sample CSV
Files2VER.csv';
$table = '`672ver`';

// get structure from csv and insert db
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($file,'r');
// first row, structure
 if ( ($data = fgetcsv($handle) ) === FALSE ) {
echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = strtolower(trim($data[$i]));
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 100);
$field_count++;
$fields[] = $f.' VARCHAR(500)';
}
}

$sqlcreate = "CREATE TABLE $table (" . implode(', ', $fields)  . ')';


echo $sqlcreate;

我觉得你可以

$sqlcreate = "CREATE TABLE $table (`" . implode("`, `", $fields)  . "`)";

如果您将字段名称括在反引号中,这将阻止它尝试将某些列名称解释为保留字...

$fields[] = '`'.$f.'` VARCHAR(500)';

以这种方式更改循环的最后一行:

$fields[] = '`' . $f . '` VARCHAR(500)';

希望一切顺利,