如何使用codeigniter导入文件

时间:2013-10-21 06:47:39

标签: codeigniter

这是我简单的PHP代码我可以使用此代码导入文件。但我必须在我的项目中实现codeigniter.how我可以更改。

<?php 

$connect = mysql_connect('localhost','root','12345');
if (!$connect) { 
    die('Could not connect to MySQL: ' . mysql_error()); 
} 

$cid =mysql_select_db('test',$connect); 
// supply your database name

define('CSV_PATH','C:/wamp/www/csvfile/'); 
// path where your CSV file is located

    $csv_file = CSV_PATH . "infotuts.csv"; // Name of your CSV file
    $csvfile = fopen($csv_file, 'r');
    $theData = fgets($csvfile);
    $i = 0;
    while (!feof($csvfile)) {
        $csv_data[] = fgets($csvfile);
        $csv_array = explode(",", $csv_data[$i]);
        $insert_csv = array();
        $insert_csv['ID'] = $csv_array[0];
        $insert_csv['name'] = $csv_array[1];
        $insert_csv['email'] = $csv_array[2];
        $query = "INSERT INTO csvdata(ID,name,email) 
VALUES('','".$insert_csv['name']."','".$insert_csv['email']."')";
        $n=mysql_query($query, $connect );
        $i++;
    }
    fclose($csvfile);

echo "File data successfully imported to database!!";
mysql_close($connect);
?>

这段代码工作正常,但我必须更改codeigniter.please指南如何.................在codeigniter中实现此代码........ ....它如何在ci中工作................

1 个答案:

答案 0 :(得分:2)

就像这样:

/*
$connect = mysql_connect('localhost','root','12345');
if (!$connect) { 
    die('Could not connect to MySQL: ' . mysql_error()); 
} 

$cid =mysql_select_db('test',$connect); 
// supply your database name

*/

class something extends CI_Controller{


    function import(){
        define('CSV_PATH','./csvfile/');    #make a folder "csvfile" in your project root 
        // path where your CSV file is located

            $csv_file = CSV_PATH . "infotuts.csv"; // Name of your CSV file
            $csvfile = fopen($csv_file, 'r');
            $theData = fgets($csvfile);
            $i = 0;
            while (!feof($csvfile)) {
                $csv_data[] = fgets($csvfile);
                $csv_array = explode(",", $csv_data[$i]);
                $insert_csv = array();
                $insert_csv['ID'] = $csv_array[0];
                $insert_csv['name'] = $csv_array[1];
                $insert_csv['email'] = $csv_array[2];
                //$query = "INSERT INTO csvdata(ID,name,email) VALUES('','".$insert_csv['name']."','".$insert_csv['email']."')";
                //$n=mysql_query($query, $connect );
                //$i++;
                $this->model->save_data( $insert_csv );
            }
            fclose($csvfile);

        echo "File data successfully imported to database!!";
    }
}


/*
mysql_close($connect);
*/


#model function
function save_data( $save_data ){
    $this->db->insert('table_name', $save_data ); #edited here
    echo $this->db->last_query();
    return 1;
}

然后像这样调用import function

http://domain.com/something/import