gpt4 book ai didi

php - 如何在使用 implode 时将附加数据插入 mysql

转载 作者:行者123 更新时间:2023-11-29 14:40:40 25 4
gpt4 key购买 nike

这是代码:

    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) 。它没有单引号,所以我插入记录时出错。我可以知道如何解决这个问题吗?

最佳答案

试试这个:

$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);

关于php - 如何在使用 implode 时将附加数据插入 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8061772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com