我正在使用以下函数将csv文件导入db。一切都很好。但我也希望它还插入$_SESSION['userid']
CSV文件。请帮我。谢谢
function csv_file_to_mysql_table($source_file, $target_table, $max_line_length=10000) {
if (($handle = fopen("$source_file", "r")) !== FALSE) {
$columns = fgetcsv($handle, $max_line_length, ",");
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
$insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while (count($data)<count($columns))
array_push($data, NULL);
$query = "$insert_query_prefix (".join(",",quote_all_array($data)).");";
mysql_query($query);
}
fclose($handle);
}
}
function quote_all_array($values) {
foreach ($values as $key=>$value)
if (is_array($value))
$values[$key] = quote_all_array($value);
else
$values[$key] = quote_all($value);
return $values;
}
function quote_all($value) {
if (is_null($value))
return "NULL";
$value = "'" . mysql_real_escape_string($value) . "'";
return $value;
}
csv_file_to_mysql_table($uploadfile,"import_csv");
echo "file is imported successfully!";
}
答案 0 :(得分:0)
我想这样的事情会起作用。只需在执行数组连接后附加额外的字段。
我不知道你的user_id列被调用了什么,我只是假设了user_id
$insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).",user_id)\nVALUES";
将user_id值添加到values参数
$query = "$insert_query_prefix (".join(",",quote_all_array($data)).",".$_SESSION['userid'].");";
答案 1 :(得分:0)
查找“ADD HERE”...只需在获取列名后添加列名称,并在构建完数据后将数据添加到数组的末尾...应该很简单。
foreach ($columns as &$column) {
$column = str_replace(".","",$column);
}
//ADD HERE
$columns[] = "userid";
$insert_query_prefix = "INSERT INTO $target_table (".join(",",$columns).")\nVALUES";
while (($data = fgetcsv($handle, $max_line_length, ",")) !== FALSE) {
while (count($data)<count($columns))
array_push($data, NULL);
//ADD HERE
$data[] = $_SESSION['userid']
$query = "$insert_query_prefix (".join(",",quote_all_array($data)).");";
mysql_query($query);