1

I want to insert data from a CSV file to a MySQL table. For that right now I use the following code, but when I upload the file my browser becomes not-responding. And after few times a pop-up displays that says to restart Firefox or quit Firefox. I just want to know, where is my fault in the given code?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="" content="">
</head>
<body>
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="imageup" /><input type="submit" name="submit" value="Upload"/>
    </form>
</body>
</html>
<?php
    function generateRandomString($length = 10){
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $randomString = '';
            for($i = 0; $i < $length; $i++){
                $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

if(isset($_POST['submit'])){
    $t= generateRandomString();
    $path = 'csv/';
    $image = $_FILES["imageup"]["name"];
//  $tmp = explode(".",$image);
    $type = end($tmp);
    $file = array("csv");
    $csv_file = $path.$image;

    if(in_array(strtolower($type), $file)){
        if(move_uploaded_file($_FILES["imageup"]["tmp_name"], $path.$image)){
            readfile($_FILES['imageup']['tmp_name']);

            $open = fopen($_FILES['imageup']['tmp_name'], 'r');
            $theData = fgets($open);
            $i = 0;

            while(!feof($open)){
                $csv_data[] = fgets($open, 1024);
                $csv_array = explode(",", $csv_data[$i]);
                $insert_csv = array();
                $insert_csv['ID'] = $csv_array[0];
                $insert_csv['firstname'] = $csv_array[1];
                $insert_csv['lastname'] = $csv_array[2];
                $insert_csv['email'] = $csv_array[3];

                $isql = "INSERT INTO `myguests`(`id`, `firstname`, `lastname`, `email`) VALUES ('','".$insert_csv['firstname']."','".$insert_csv['lastname']."','".$insert_csv['email']."')";
                $run = mysqli_query($con, $isql);
                $i++;               
            }
            fclose($open);

            echo "File upload successfully";
            mysqli_close($con);
        }
    }
    else{
        echo "Not valid file formate";
    }
}
?>
Manya Singh
  • 131
  • 1
  • 1
  • 10

2 Answers2

0
Please try this I have provide some php code for import data csv format 
<body>
<div id="container">
<div id="form">

<?php
$deleterecords = "TRUNCATE TABLE tablename"; //empty the table of its current records
mysql_query($deleterecords);

//Upload File
if (isset($_POST['submit'])) {

    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded 
 successfully." . "</h1>";
        echo "<h2>Displaying contents:</h2>";
        readfile($_FILES['filename']['tmp_name']);
    }

    //Import uploaded file to Database
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $import="INSERT into importing(text,number)values('$data[0]','$data[1]')";

        mysql_query($import) or die(mysql_error());
    }

    fclose($handle);

    print "Import done";

//view upload form
} else {

    print "Upload new csv by browsing to file and clicking on Upload<br />\n";

    print "<form enctype='multipart/form-data' action='upload.php' method='post'>";

    print "File name to import:<br />\n";

    print "<input size='50' type='file' name='filename'><br />\n";

    print "<input type='submit' name='submit' value='Upload'></form>";

}

?>

</div>
</div>
</body>  
sujeet gupta
  • 139
  • 6
  • Yo want more description please use this link http://stackoverflow.com/questions/11448307/importing-csv-data-using-php-mysql – sujeet gupta Dec 20 '14 at 09:26
0

I thing your not making here Database Connection .Check Your database Connetion properly

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection

$conn = new mysqli($servername, $username, $password,$dbname);

Remove Commnt here // $tmp = explode(".",$image);

  • its works fine >>check this link http://coyotelab.org/php/upload-csv-and-insert-into-database-using-phpmysql.html – Shefeek Niyas TP Dec 20 '14 at 12:23
  • first make database connection >> – Shefeek Niyas TP Dec 20 '14 at 12:25
  • //Upload File if (isset($_POST['submit'])) { if (is_uploaded_file($_FILES['filename']['tmp_name'])) { echo "

    " . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "

    "; echo "

    Displaying contents:

    "; readfile($_FILES['filename']['tmp_name']); } //Import uploaded file to Database $handle = fopen($_FILES['filename']['tmp_name'], "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $import="INSERT into users(firstname,lastname) values('$data[0]','$data[1]')"; mysql_query($import) or die(mysql_error()); }
    – Shefeek Niyas TP Dec 20 '14 at 12:25
  • fclose($handle); print "Import done"; //view upload form }else { print "Upload new csv by browsing to file and clicking on Upload
    \n"; print "
    "; print "File name to import:
    \n";
    – Shefeek Niyas TP Dec 20 '14 at 12:26
  • print "
    \n"; print ""; } ?>
    – Shefeek Niyas TP Dec 20 '14 at 12:26