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

為{幸葍}努か 提交于 2019-12-11 03:42:13

问题


I have a php code that will create a table to mysql database using a csv file. However, some column headers are not being read by mysql. The only time that mysql will read the query is when I add backticks(`). Can you help me on where to put backticks in my query? :(

Here's my code:

   $file = 'C:\Users\user\Desktop\Sample CSV
Files\672VER.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;

回答1:


If you enclose the field name in backticks, this will stop it trying to interpret some column names as reserved words...

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



回答2:


Change the last line of the loop this way:

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

I hope it works fine,




回答3:


I think you could do

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


来源:https://stackoverflow.com/questions/44537093/add-backticks-in-creating-table-to-mysql-with-csv-file-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!