将具有不同列数的csv文件插入mysql表

时间:2013-05-02 13:50:34

标签: php mysql csv

尝试使用php命令fcsvget将csv文件中的一些数据插入到mysql表中,但是很快就会有人告诉我哪里出错了。我在加载页面时没有数据输入和错误。

csv文件具有与其进入的表不同的标题名称和列数。

这是我目前的代码。

<?php

// set local variables
$connect = mysql_connect("localhost","db","password") or die('Could not connect: ' . mysql_error());
$handle = fopen("test.csv", "r");

// connect to mysql and select database or exit 
mysql_select_db("db", $connect);

// loop content of csv file, using comma as delimiter

while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$Product_ID = $data[0];
$Model = $data[1];

// entry insert
$query = "INSERT into products_test  (products_id, products_model) VALUES '$Product_ID', $Model";


mysql_query($query);
if (mysql_affected_rows() <= 0) {

// no rows where affected by update query
}
} else {
// entry doesn't exist continue or insert...
}

mysql_free_result($result);
}

fclose($handle);
mysql_close($connect);

?>

2 个答案:

答案 0 :(得分:0)

检查您的代码..

    } else {
     // entry doesn't exist continue or insert...
    }

没有效果,因为没有IF开始。一个

   if (mysql_affected_rows() <= 0) {

    // no rows where affected by update query
  }

在'Else'声明之前已经关闭。我无法接受你的查询,但这是我第一次看到的

答案 1 :(得分:0)

while (($data = fgetcsv($handle, 10000, "|")) !== false) {
$Product_ID =  $data[0];
$Model = $data[1];
$HighPic = $data[2];
$ManuId = $data[3];
$parent_id = $data[7];
$Image = $data[13];
$Price = $data[14];
$Supplier = $data[15];
$Stock = $data[17];



// entry insert
$query = "INSERT into products_test (products_id, products_model, products_image, manufacturers_id, products_parent_id, icecat_manfimg, products_price, icecatcode, products_quantity) VALUES ($Product_ID, $Model, $HighPic, $ManuId, $parent_id, $Image, $Price, $Supplier, $Stock)" ;

mysql_query($query);
} 

mysql_free_result($result);


fclose($handle);
mysql_close($connect);

?>