Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to import csv file into mysql database in php

    • 0
    • 3
    • 3
    • 1
    • 0
    • 0
    • 0
    • 0
    • 577
    Comment on it

    To Import csv file into mysql database using php script follow the below code:

    For example: I have a .csv file data with this formate:-

    (1) Indresh Singh, indresh@abc.com, 12345
    (2) mukul kant, mukul.kant@abc.com, 12345

    To insert this data into database, I am using the fallowing code below-

    1. <?php
    2. //Database connection
    3. $db = mysql_connect("localhost", "root", "123456");
    4. if(!$db){
    5. echo 'Mysql Connection Error';
    6. }
    7. if(!mysql_select_db("import",$db)){
    8.  
    9. echo 'Database Not Present'.mysql_error();
    10. }
    11. $deleterecords = "TRUNCATE TABLE users";
    12. //use for empty the table of its current records
    13. mysql_query($deleterecords);
    14.  
    15. //Upload File
    16. if (isset($_POST['submit'])) {
    17.  
    18. //Import the uploaded file into Database
    19. $handle = fopen($_FILES['filename']['tmp_name'], "r");
    20.  
    21. while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    22.  
    23. $importQuery = "INSERT INTO users(name,email,password) VALUES ('".$data[0]."','".$data[1]."','".$data[2]."')";
    24.  
    25. mysql_query($importQuery);
    26. }
    27.  
    28. fclose($handle);
    29. echo 'File Impot Successfully';
    30. //view upload form
    31. }else {
    32.  
    33. #Html file tag includes#
    34. }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: