Hari Hari - 3 months ago 14
PHP Question

Import csv file data into database

I have to write a code were i need to import the email ids of people with their names which will be on a excel sheet into the database, but the issue which am facing is its displaying me invalid file where as file is in .csv format,please help, am new to this concept,pardon me if i went wrong somewhere.

import.php

<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="sel_file" size="20" /><br />
<input type="submit" name="submit" value="Submit" />
</form>

<?php
include ("connection.php");

if(isset($_POST["submit"]))
{
$fname = $_FILES['sel_file']['tmp_name'];
echo'Upload file name is'.$fname.' ';
$chk_ext = explode(".",$fname);

if(strtolower(end($chk_ext)) == "csv"){

$filename = $_FILES['sel_file'] ['tmp_name'];
$handle = fopen($filename, "r");

while(($data = fgetcsv($handle, 1000, ",")) !== false)
{
$sql = "INSERT into import_email (vault_no, name, email) values ('".$_SESSION['vault_no']."', '$data[0]', '$data[1]')";
mysql_query($sql) or die(mysql_error());
}
fclose($handle);
echo "Successfully imported! ";
}else{
echo "Invalid file!";
}
}
?>

Answer

You are using temp name instead of name

   $_FILES['sel_file'] ['tmp_name'];

change this to :

   $_FILES['sel_file'] ['name'];

example of $_FILE['input_file'] is

[input_file] => Array
    (
        [name] => MyFile.jpg //<-------- This is the one you should use because it contains the extension (that you are checking for)
        [type] => image/jpeg
        [tmp_name] => /tmp/php/php6hst32 //<----------- this is the one you used 
        [error] => UPLOAD_ERR_OK
        [size] => 98174
    )

So your PHP part should look like this:

    <?php
    include("connection.php");

    if (isset($_POST["submit"])) {
        $fname = $_FILES['sel_file']['name']; // Changed only this
        echo 'Upload file name is' . $fname . ' ';
        $chk_ext = explode(".", $fname);

        if (strtolower(end($chk_ext)) == "csv") {

            $filename = $_FILES['sel_file'] ['tmp_name'];
            $handle = fopen($filename, "r");

            while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                $sql = "INSERT into import_email (vault_no, name, email) values ('" . $_SESSION['vault_no'] . "', '$data[0]', '$data[1]')";
                mysql_query($sql) or die(mysql_error());
            }
            fclose($handle);
            echo "Successfully imported! ";
        } else {
            echo "Invalid file!";
        }
    }
    ?>
Comments