我有一个将CSV文件插入数据库的功能。我的项目使用Yii Framework,但这个类与Yii没有关系。
我导入成功,但在打印导入的行数时遇到问题。
我的课程(多个文件,但只有一个文件):
class LsuController extends BackEndController {
public function dbconfig(){
$dbconfig = array();
$dbconfig['dsn'] = 'mysql:host=localhost;dbname=bs_dev_csueastbay';
$dbconfig['username'] = 'root';
$dbconfig['password'] = '';
return $db = new PDO($dbconfig['dsn'], $dbconfig['username'], $dbconfig['password']);
}
public function actionIndex() {
// Config database
$db = $this->dbconfig();
$has_err = 0;
$link = dirname(__FILE__)."/../../../runtime/Import/";
$handles = array();
$handles[] = fopen($link."bookPictureMappings.csv","r");
foreach ($handles as $handle) {
if(!$handle){
$has_err++;
}
}
if($has_err == 0){
foreach ($handles as $key=>$handle) {
switch ($key) {
case '0':
$i = 0;
$model_err = 0; $ss = 0;
do {
if (isset($data[0])) {
if($i > 0){
$sql="INSERT INTO bookpicturemappings (Id, BookId, PictureId, bookpicturemappings.Order) VALUES (
:Id, :BookId, :PictureId, :bookOrder)";
$command = $db->prepare($sql);
$command->bindParam(":Id",$data[0],PDO::PARAM_STR);
$command->bindParam(":BookId",$data[1],PDO::PARAM_STR);
$command->bindParam(":PictureId",$data[2],PDO::PARAM_STR);
$command->bindParam(":bookOrder",$data[3],PDO::PARAM_STR);
if ($command->execute()){
$ss++;
}
}
$i++;
}
} while ($data = fgetcsv($handle,0,",","\""));
echo "Insert bookpicturemappings.csv successful! Total: ".($i-1)." - Import: ".$ss." - Error: ".$model_err."<br>";
break;
...............................
这里的问题:
插入bookpicturemappings.csv成功!总计:1862 - 进口:0 - 错误:0
if ($command->execute()){ $ss++; } var_dump($ss);
结果是($ ss = 1862):
&lt; ... value dump ....&gt;
插入bookpicturemappings.csv成功!总计:1862 - 进口:1862 - 错误:0
WT ...?我不明白为什么?
答案 0 :(得分:0)
检查$ handle中的最新项目,我猜它是空的(文件末尾的换行符?)并且$ ss设置为0但不循环。
修改强>
您的上一次迭代为false,但仅在执行块后检查该条件。
尝试抛弃do并像这样使用while:
while ($data = fgetcsv($handle,0,",","\"")){
if (isset($data[0])) {
if($i > 0){
$sql="INSERT INTO bookpicturemappings (Id, BookId, PictureId, bookpicturemappings.Order) VALUES ( :Id, :BookId, :PictureId, :bookOrder)";
$command = $db->prepare($sql);
$command->bindParam(":Id",$data[0],PDO::PARAM_STR);
$command->bindParam(":BookId",$data[1],PDO::PARAM_STR);
$command->bindParam(":PictureId",$data[2],PDO::PARAM_STR);
$command->bindParam(":bookOrder",$data[3],PDO::PARAM_STR);
if ($command->execute()){
$ss++;
}
}
$i++;
}
};