如何从PHP导入Excel文件到mysql数据库

前端之家收集整理的这篇文章主要介绍了如何从PHP导入Excel文件到mysql数据库前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
让我们说,
我想从 PHP导入/上传excel文件MysqL

我的HTML如下

<form enctype="multipart/form-data" method="post" 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>

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= 'product_record'; // 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");
        //$sql_data = "SELECT * FROM prod_list_1 ";
        while (($emapData = fgetcsv($file,10000,",")) !== FALSE)
        {
            //print_r($emapData);
            //exit();
            $sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
            MysqL_query($sql);
        }
        fclose($file);
        echo 'CSV File has been successfully Imported';
        header('Location: index.PHP');
    }
    else
        echo 'Invalid File:Please Upload CSV File';
}
?>

Excel文件如下

我想仅将第二行值导入到我的表中.请帮助我如何解决它或给我任何资源.我能够上传excel文件,但格式不正确.我想在MysqL的4列中上传4列,但是它正在上传MysqL的1列中的所有4列.我错过了什么吗?

对于> =第二行值插入到table-
$file = fopen($filename,"r");
//$sql_data = "SELECT * FROM prod_list_1 ";

$count = 0;                                         // add this line
while (($emapData = fgetcsv($file,")) !== FALSE)
{
    //print_r($emapData);
    //exit();
    $count++;                                      // add this line

    if($count>1){                                  // add this line
      $sql = "INSERT into prod_list_1(p_bench,'$emapData[3]')";
      MysqL_query($sql);
    }                                              // add this line
}
原文链接:https://www.f2er.com/php/133003.html

猜你在找的PHP相关文章