1

这是我的简单 php 代码,我可以使用此代码导入文件。但我必须在我的项目 codeigniter 中实现。我该如何更改。

<?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。请指导如何 ........在 codeigniter 中实现此代码...... .它在ci中的工作方式......

4

1 回答 1

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
于 2013-10-21T06:59:09.160 回答