dqtm8504 2014-12-11 08:34
浏览 50
已采纳

如果CSV文件不存在,则函数继续将空行添加到数据库中

I need a little help. I have a Model file, this imports a CSV file in to the database. But my model file takes this CSV from the C:\wamp\www\cakephp-2.5.6\app\tmp\uploads\Kontaktid and if CSV file named export.csv not exsist in this folder, then my function keep adding empty rows in to database.

Can I do something like this (I tried to add this in to Controller, but this is not working) ?

If empty(Kontaktid) {

   echo ("CSV file is not found");exit;
}

This is my Controller file:

function import() {
            $this->Kontaktid->import('export.csv');
        }

And this is my Model file:

<?php  

class Kontaktid extends AppModel {
    public $validate = array(
        'title' => array('rule' => 'notEmpty'),
        'body' => array('rule' => 'notEmpty')
    );
    var $name = 'Kontaktid';
    function import($filename) {
        // set the filename to read CSV from
        $filename = TMP . 'uploads' . DS . 'Kontaktid' . DS . $filename;
        // open the file
        $handle = fopen($filename, "r");
        // read the 1st row as headings
        $header = fgetcsv($handle);
        // read each data row in the file
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $this->query ("INSERT into kontaktids(id,Eesnimi,Perenimi,Maakond,Linn,Tanav,Maja,Telefon,lisanumbrid) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')");
            $this->query;
        }
         print "Import done";
        // close the file
        fclose($handle);
    }
}

Thanks for helping !

  • 写回答

3条回答 默认 最新

  • doushi4956 2014-12-11 08:38
    关注

    You can do it using :

    <?php
    $filename = '/path/to/export.csv';
    
    if (file_exists($filename)) {
        // do your import stuff.
    } else {
        // File is not exist.
    }
    ?>
    

    Check this link for more info : http://php.net/manual/en/function.file-exists.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀