doukang2003 2016-01-13 07:54
浏览 104
已采纳

如何将CSV表插入Mysql数据库?

I have a simple uploading page that will allow a user to upload CSV file into the server.

After the uploading, the page will display the CSV file into an html table format

Code to Display CSV File to HTML:

<?php
echo "<table class='tbl1'>

";

echo "<tr>";
echo "<th>GOUP NO</th>";
echo "<th>PID CODE</th>";
echo "<th>ID CODE</th>";
echo "<th>DESCRIPTION</th>";
echo "</tr>";

$f = fopen("upload\micro_center.csv", "r");
while (($line = fgetcsv($f)) !== false) {
    echo "<tr>";
    foreach ($line as $cell) {
            echo "<td>" . htmlspecialchars($cell) . "</td>";
    }
    echo "</tr>
";
}
fclose($f);
echo "
</table>";
?>

I want to add a query on how to insert the data in the CSV file or displayed html table into MSSQL database.

Note: Table headers and Database Table Columns are with the same name

CSV File:

0,G068,CNDLDS,Candelaria District
0,CNDLDS,CNDLDSA,Babancal ES
0,CNDLDS,CNDLDSB,Binabalian ES
0,CNDLDS,CNDLDSC,Candelaria Central
0,CNDLDS,CNDLDSD,Catol ES

Thank You for your answers

  • 写回答

1条回答 默认 最新

  • douju9847 2016-01-13 08:17
    关注

    Use the below code:

    //get the csv file 
    $file = $_FILES[csv][tmp_name];  // your csv file here
    $handle = fopen($file,"r"); 
    
    //loop through the csv file and insert into database 
    do { 
        if ($data[0]) { 
            mysql_query("INSERT INTO your table (GOUP_NO, PID_CODE, ID_CODE, DESCRIPTION) VALUES 
                ( 
                    '".addslashes($data[0])."', 
                    '".addslashes($data[1])."', 
                    '".addslashes($data[2])."',
                    '".addslashes($data[3])."'  
                ) 
            "); 
        } 
    } while ($data = fgetcsv($handle,1000,",","'")); 
    // 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决