doucai1901 2014-07-22 07:04
浏览 73

使用php将csv文件转换为mysql数据库

I have a csv file like the one below and I want to convert it to a msql database. In my csv file there are so many lines I want to find a quick way to copy everything. Someone tell me would know what to look for or kindly post the code used? Thank you! This is the example of csv file that I need to copy in db

Numero SAT,Stato SAT,Tipo servizio,Data attivazione,Imei guasto,Imei consegnato,Marca terminale,Modello terminale,Famiglia guasto,Descrizione guasto
SAT100000002572,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002573,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002574,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002575,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto
SAT100000002576,in lavorazione,21/07/2014,8294121141143,8294121141143,Samsung,Nexus 4,Audio, Microfono Rotto

I tried to do with this code, someone can fix it?

<?php

$message = null;

$allowed_extensions = array('csv');

$upload_path = 'C:\xampp\htdocs\exercise-files\start';

if (!empty($_FILES['file'])) {

    if ($_FILES['file']['error'] == 0) {

        // check extension
        $file = explode(".", $_FILES['file']['name']);
        $extension = array_pop($file);

        if (in_array($extension, $allowed_extensions)) {

            if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_path.'/'.$_FILES['file']['name'])) {

                if (($handle = fopen($upload_path.'/'.$_FILES['file']['name'], "r")) !== false) {

                    $keys = array();
                    $out = array();

                    $insert = array();

                    $line = 1;

                    while (($row = fgetcsv($handle, 0, ',', '"')) !== FALSE) {

                        foreach($row as $key => $value) {
                            if ($line === 1) {
                                $keys[$key] = $value;
                            } else {
                                $out[$line][$key] = $value;

                            }
                        }

                        $line++;

                    }

                    fclose($handle);    

                    if (!empty($keys) && !empty($out)) {

                        $db = new PDO('mysql:host=localhost;dbname=satingestione', 'root', '');
                        $db->exec("SET CHARACTER SET utf8");

                        foreach($out as $key => $value) {

                            $sql  = "INSERT INTO `sgestite` (`";
                            $sql .= implode("`, `", $keys);
                            $sql .= "`) VALUES (";
                            $sql .= implode(", ", array_fill(0, count($keys), "?"));
                            $sql .= ")";
                            echo $sql;
                            echo "------------------------------------------------
";
                            //$statement = $db->prepare($sql);
                            //$statement->execute($value);

                        }

                        $message = '<span class="green">File has been uploaded successfully</span>';

                    }   

                }

            }

        } else {
            $message = '<span class="red">Only .csv file format is allowed</span>';
        }

    } else {
        $message = '<span class="red">There was a problem with your file</span>';
    }

}

?>
<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Upload CSV to MySQL</title>
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <link href="/css/core.css" rel="stylesheet" type="text/css" />
    <!--[if lt IE 9]>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
</head>
<body>

<section id="wrapper">  

    <form action="" method="post" enctype="multipart/form-data">

        <table cellpadding="0" cellspacing="0" border="0" class="table">
            <tr>
                <th><label for="file">Select file</label> <?php echo $message; ?></th>
            </tr>
            <tr>
                <td><input type="file" name="file" id="file" size="30" /></td>
            </tr>
            <tr>
                <td><input type="submit" id="btn" class="fl_l" value="Submit" /></td>
            </tr>
        </table>

    </form>

</section>

</body>
</html>
  • 写回答

2条回答 默认 最新

  • dongtong2021 2014-07-22 07:12
    关注

    This is a working example please change your code accordingly and you are Done :)

    <?php 
    
        //connect to the database
        $connect = mysql_connect("localhost","username","password");
        mysql_select_db("mydatabase",$connect); //select the table
        //
    
        if ($_FILES[csv][size] > 0) {
    
            //get the csv file
            $file = $_FILES[csv][tmp_name];
            $handle = fopen($file,"r");
    
            //loop through the csv file and insert into database
            do {
                if ($data[0]) {
                    mysql_query("INSERT INTO contacts (contact_first, contact_last, contact_email) VALUES
                        (
                            '".addslashes($data[0])."',
                            '".addslashes($data[1])."',
                            '".addslashes($data[2])."'
                        )
                    ");
                }
            } while ($data = fgetcsv($handle,1000,",","'"));
            //
    
            //redirect
            header('Location: import.php?success=1'); die;
    
        }
    
        ?>
    
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Import a CSV File with PHP & MySQL</title>
        </head>
    
        <body>
    
        <?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?> 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)