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,",","'")); 
    // 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler