这是代码:
if (($handle = fopen($source_file, "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while(count($data) < count($columns)) {
array_push($data, NULL);
}
$c = count($data);
for($i = 0; $i < $c; $i++) {
$data[$i] = "'{$data[$i]}'";
}
$sql[] = '(' . implode(',',$data) . ','.$_POST[group].')';
}
$sql = implode(',',$sql);
$query = "INSERT INTO mytable (".mysql_real_escape_string(implode(",",$columns)).",Custgroup,user_id) VALUES "
. $sql . "\n";
mysql_query($query) or trigger_error(mysql_error());
fclose($handle);
}
}
如果我的csv文件是:
姓氏,名字,性别
鲍勃啊,雄性
现在查询将是:INSERT INTO mytable (lastname,firstname,gender) VALUES ('bob','ah','male')
。
但是如果我想将额外的数据与csv文件中的数据一起插入mysql呢?
比如我有一个值$ _POST ['group'] ='family'和$ _POST ['user_id'] ='10',所以我试过了:
$sql[] = '(' . implode(',',$data) . ','.$_POST[group].','.$_POST[user_id].')';
$query = "INSERT INTO $target_table (".mysql_real_escape_string(implode(",",$columns)).",custgroup,user_id) VALUES "
. implode(',',$sql) . "\n";
但在查询中它将变为:INSERT INTO mytable (lastname,firstname,gender,custgroup,user_id) VALUES ('bob','ah','male',family,10)
。
它没有单引号,所以插入记录时出错。可以知道如何解决这个问题吗?
答案 0 :(得分:1)
试试这个:
$sql[] = '(' . implode(',', $data) . ", '" . $_POST['group'] . "'," . $_POST['user_id'] . ')';
$query = "INSERT INTO $target_table (" . mysql_real_escape_string(implode(',', $columns)) . ',custgroup,user_id) VALUES ' . implode(',', $sql);
答案 1 :(得分:0)
为了便于阅读,您可以考虑以下内容:
$sql = sprintf("(%s,'%s',%d)",
implode(',', $data),
$_POST['group'],
$_POST['user_id']
);
可以让您更灵活地理解代码的实际执行情况。