我现在有使用PHP的CSV上传项目的工作代码。我目前的问题是关于多个表/查询。我有200个字段变量建立到列数组和6个表数组保存相应的值。所有这些表共享一些属性,因此字段1到10将进入其中5个表,而有些表是特定于表的。如果我上传CSV并立即以我的HTML表单提交,那么所有内容都会提交,但只能在我的数组的最后一个表中提交,它应该插入到每个表中。代码示例:
表格数组:
$table_cols = array();
/*staging*/
$table_cols[0] = "orderNumber,place,workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName";
/*clients*/
$table_cols[1] ="orderNumber,place,workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName";
/*meters*/
$table_cols[2] ="workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName,address,locID";
/*tests*/
$table_cols[3] ="workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName,address,locID";
/*costs*/
$table_cols[4] ="workOrderNum,onsiteSurveyTestCost,onsiteSurveyTestRepairCost,offsiteSurveyTestCost";
/*workorders*/
$table_cols[5] ="workOrderNum,lowSideMIUNum,highSideMIUNum,accountNum,custName,address";
$tablenames = array("staging","clients","meters","tests","costs","workorders");
循环代码:
for($tableno = 0;$tableno < sizeof($tablenames);$tableno++){
$q = "";
$col_list = '`'.str_replace(',','`,`',$table_cols[$tableno]).'`';
$q .= "INSERT INTO ".$tablenames[$tableno]." (".$col_list.") VALUES (";
$cols = explode(",",$table_cols[$tableno]);
$data = array();
foreach($cols as $key => $fldname) {
$data[] = "'".$coldata[$fldname]."'";
}
$q .= implode(",",$data).");";
echo "<p>\$q:<pre>".print_r($q,true)."</pre></p>\n";
}
if(mysqli_multi_query($connect, $q)) { echo'File submitted'; } else { /*var_dump($q)*/echo "Error: " . mysqli_error($connect); }
}
没有PHP错误,没有语法问题,其他一切都很好。我只需要弄清楚多查询代码为什么不允许多个表条目。
更新 尝试新插入:
for($tableno = 0;$tableno < sizeof($tablenames);$tableno++){
$q = "";
$col_list = '`'.str_replace(',','`,`',$table_cols[$tableno]).'`';
$q .= "INSERT INTO ".$tablenames[$tableno]." (".$col_list.") VALUES (";
$cols = explode(",",$table_cols[$tableno]);
$data = array();
foreach($cols as $key => $fldname) {
$data[] = "'".$coldata[$fldname]."'";
}
$q .= implode(",",$data).");";
$q2 .= "INSERT INTO clients ('orderNumber','place','workOrderNum','lowSideMIUNum','highSideMIUNum','accountNum','custName','address','locID','date','utility','serialNumber','serviceName','address2','servicePreformed')
SELECT 'orderNumber','place','workOrderNum','lowSideMIUNum','highSideMIUNum','accountNum','custName','address','locID','date','utility','serialNumber','serviceName','address2','servicePreformed'
FROM staging;";
echo "<p>\$q:<pre>".print_r($q,true)."</pre></p>\n";
echo "<p>\$q:<pre>".print_r($q2,true)."</pre></p>\n";
}
if(mysqli_multi_query($connect, $q)) { echo'File submitted'; } else { /*var_dump($q)*/echo "Error: " . mysqli_error($connect); }
}
成功消息显示文件插入成功,但它没有填充我的客户端表,但它仍然执行第一个查询并插入到暂存中。