简体   繁体   中英

exporting ang retrieving data from excel to database using php

I am trying to create a feature in my program where in you could upload data to the database by uploading data from excel (uploading excel file) i have provided the code below but the data in the database is encoded(i provided a screenshot). is there something wrong with the code?

Excel format:

firstname lastname
_____________________
amir       kumar
jhon         doee

But this is what the data looks like when inserted into the database:

在此处输入图片说明

This is my index.php:

 <form enctype="multipart/form-data" method="post" action="import.php" role="form">
        <div class="form-group">
            <label for="exampleInputFile">File Upload</label>
            <input type="file" name="file" id="file" size="150">
            <p class="help-block">Only Excel/CSV File Import.</p>
        </div>
        <button type="submit" class="btn btn-default" name="Import" value="Import">Upload</button>
    </form>

import.php

<?php 
if(isset($_POST["Import"]))
{   
    //First we need to make a connection with the database
    $host='localhost'; // Host Name.
    $db_user= 'root'; //User Name
    $db_password= '';
    $db= 'testdatabase'; // Database Name.
    $conn=mysql_connect($host,$db_user,$db_password) or die (mysql_error());
    mysql_select_db($db) or die (mysql_error());
    echo $filename=$_FILES["file"]["tmp_name"];
    if($_FILES["file"]["size"] > 0)
    {
        $file = fopen($filename, "r");
        $count = 0;
        $sql_data = "SELECT * FROM person";
        echo $sql_data;
        while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
        {
            //print_r($emapData);
            //exit();
            $count++;
            if($count > 1) {
            $sql = "INSERT into person(firstname , lastname) values ('$emapData[0]','$emapData[1]')";
            mysql_query($sql);
            echo "success";

        }
        }
        fclose($file);
        echo 'CSV File has been successfully Imported';
        header('Location: index.php');
    }
    else
        echo 'Invalid File:Please Upload CSV File';
}
?>

Don't use the Excel file as is. You see what gibberish you get.

Instead, do one of these:

  • "Export" the data from Excel into a .csv file, then LOAD DATA into MySQL.

  • Use a PHP API that lets you fetch data from Excel. Then INSERT the data into a MySQL table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM