PHP - 阅读多行CSV

时间:2017-04-06 13:29:38

标签: php sql database csv fgetcsv

在上传后读取CSV的第一行然后插入数据库时​​,我没有任何问题,但多行任务存在问题。我现在可以在网页上打印一个数组转储,显示CSV的所有行,但它仍然只是将第一行插入我的数据库。我已经完成了我的代码并想出了这个:

if(isset($_POST['submit']))
{
ini_set('auto_detect_line_endings', true);

$file = $_FILES["file"]["tmp_name"];
$handle = fopen($file, "r");

 while(!feof($handle)){
$filesop = print_r(fgetcsv($handle, 0, ","));
 }
$coldata = array();

我有这个代码用于调用查询(此后还有其他查询,但这是放入该临时表的主要查询):

 $tablenames = array("staging"/*,"clients","meters","tests","costs","workorders"*/);

for($tableno = 0;$tableno < sizeof($tablenames);$tableno++){
$q = "";
$q2 = "";
$q3 = "";
$q4 = "";
$q5 = "";
$q6 = "";
$col_list = '`'.str_replace(',','`,`',$table_cols[$tableno]).'`';
$q .= "INSERT INTO ".$tablenames[$tableno]." (".$col_list.") VALUES (";
$last_id = mysqli_insert_id($connect);
$cols = explode(",",$table_cols[$tableno]);
$data = array();
foreach($cols as $key => $fldname) {
    $data[] = "'".$coldata[$fldname]."'";
}

/*INSERT INTO STAGING TABLE - INITAL CSV UPLOAD*/
$q .= implode(",",$data).");";

我在查询中做错了什么导致它不将CSV的所有行都插入到数据库中?

0 个答案:

没有答案