将CSV文件导入mysql,将现有的mysql表与csv文件的头匹配

时间:2012-04-23 03:00:02

标签: php mysql fgetcsv

我在匹配方面遇到了困难。 我在mysql表中创建了标题字段为“CaseNumber”,“Incident”和“Location” 并且在CSV文件中它包含的列数多于我的表,例如“CaseNumber”,“IncidentDate”,“IncidentTime”,“Incident”和“Location”。 所以我正在匹配标题,所以只有匹配的列才会被加载到我的表中。 以下是codes.Any建议代码来自这里?

<?php

    $query='';
    $link = mysql_connect('localhost', 'root', '');
    if(!$link){
    die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("csv",$link);

    if(!isset($_POST['option']))
    {
        echo $page;
    }

    elseif($_POST['option']=="yes")
    {
        $handle = fopen("gatech.csv", 'r');

        while(($fileop = fgetcsv($handle, 100,","))!== false)
        {
                            if (in_array('CaseNumber', $fileop, true)) {
            $var = array_search('CaseNumber', $fileop);
            $Case_Number = $fileop[$var];
        }
        else if (in_array('IncidentDate', $fileop, true)) {
            $var = array_search('IncidentDate', $fileop);
            $IncidentDate_ = $fileop[$var];
        }
        else if (in_array('IncidentTime', $fileop, true)) {
            $var = array_search('IncidentTime', $fileop);
            $IncidentTime_ = $fileop[$var];
        }
        else if (in_array('Location', $fileop, true)) {
            $var = array_search('Location', $fileop);
            $Location_ = $fileop[$var];
        }
        else if (in_array('Incident', $fileop, true)) {
            $var = array_search('Incident', $fileop);
            $Incident_ = $fileop[$var];
        }
        else if (in_array('Diposition', $fileop, true)) {
            $var = array_search('Diposition', $fileop);
            $Diposition_ = $fileop[$var];
        }               
            $sql = mysql_query("INSERT INTO test (CaseNumber, IncidentDate, IncidentTime, Location, Incident, Disposition) VALUES ('$Case_Number','$Incident_Date','$Incident_Time','$Location_','$Disposition_','$Incident_')");

        }
        if($sql)
        {
            echo 'data uploaded successfully';
        }
        else
            echo 'failed';
        }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Untitled</title>
    <link rel="stylesheet" type="text/css" href="../style/style.css"/>
    <script type="text/javascript" src="http://ajax.google.apis.com/ajax/libs/jquery/1.3.2/
</head>
<body>
    <div id="mainWrapper">

        <form method="post" action="index.php" enctype="multipart/form-data">
            <input type="file" name="file" />
            <br/>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </div>
</body>
</html>

0 个答案:

没有答案