• How to Import the contents of CSV files into MySQL Database using PHP

    Step1: create a database with name test and create table user
    Step2: Put a csv file (which you want to import) into your document

    root.
    Step3: Established database connection and first open the file in read

    mode, using fgets () all data will be collected in an array and that

    array will be stored in database.

    Create user table:

    1
    2
    3
    4
    5
    6
    
    CREATE TABLE IF NOT EXISTS `user` (
    `ID` int(10) NOT NULL AUTO_INCREMENT,
    `name` varchar(50) NOT NULL,
    `email` varchar(50) NOT NULL,
    PRIMARY KEY (`ID`)
    )

    Code For csv-import.php:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    
    <?php
     
    $connect = mysql_connect('hostname','username','password');
    if (!$connect) {
    die('Could not connect to MySQL: ' . mysql_error());
    }
     
    $cid =mysql_select_db('test',$connect);
    // supply your database name
     
    define('CSV_PATH','C:/xampp/htdocs/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, 1024);
    $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[ID]."','".$insert_csv['name']."','".$insert_csv
     
    ['email']."')";
    $n=mysql_query($query, $connect );
    $i++;
    }
    fclose($csvfile);
     
    echo "File data successfully imported to database!!";
    mysql_close($connect);
    ?>

Comments on this post

Leave a Reply

  • Security Code :


    7 + = thirteen