使用Csv文件更新数据库

时间:2014-02-16 13:55:41

标签: php csv

当我上传Csv文件时,它总是说“不正确的表”。

我检查了表名,这是正确的 但我仍然不知道为什么它不更新数据库。 可以使用Csv文件更新数据库吗?或者只能插入?

<?php
include 'connect.php';
$modname = $user_data['name'];
$usy = $_POST['usy'];
$usem = $_POST['usem'];
$term2 = $_POST['term2'];
if ( isset( $_FILES['userfile'] ) )
{
  $csv_file = $_FILES['userfile']['tmp_name'];

  if ( ! is_file( $csv_file ) )
    exit('File not found.');



  if (($handle = fopen( $csv_file, "r")) !== FALSE)
  {
      fgetcsv($handle); // get line 0 and move pointer to line 1
      fgetcsv($handle); // get line 1 and move pointer to line 2
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
      {  
        {
        $sql = "UPDATE `$term2` SET grade = $data[1] WHERE name_id = $data[0], section = $data[4], subject = $data[5], uploaded = $modname, school_year = $usy , semester = $usem"; 
        $exec = mysql_query($sql) or die(mysql_error());
        $sql2 = "DELETE FROM `$term2` WHERE `name_id` = '' AND `grade` = '';";  
        $exec = mysql_query($sql2) or die(mysql_error());   

        echo ("The following data has been added to the database");
        }
      }
    }
  }
?>
<form name="form2" enctype="multipart/form-data" method="POST" onSubmit="return validateForm()">
    <H1>Update CSV File</H1>
    School Year:<input type="text" name="usy"> Semester:    <select type="text" name="usem">
    <option value="1st">1st</option>
    <option value="2nd">2nd</option>
    </select>
    <br />
    Term:       <select type="text" name="term2">
    <option value="prelims">Prelims</option>
    <option value="midterm">Midterm</option>
    <option value="prefinals">Prefinals</option>
    <option value="finals">Finals</option>
    </select>
    <br />
    <br />
    <input name="userfile" type="file">
    <br />
    <input type="submit" value="Upload">



        </form>

2 个答案:

答案 0 :(得分:0)

您的sql语句中似乎出现了错误

$sql = "UPDATE `$term2` SET grade = $data[1] WHERE name_id = $data[0], section = $data[4], subject = $data[5], uploaded = $modname, school_year = $usy , semester = $usem"; 

WHERE子句必须使用AND / OR代替逗号(,)才能添加条件。逗号应该用于分隔您希望通过更新设置的列/字段。

答案 1 :(得分:0)

您的查询中有一个缺陷: “$ sql =”UPDATE $term2 SET等级= $ data [1] WHERE ...“ 从$term2中删除$,它应显示为: “$ sql =”UPDATE term2 SET等级= $ data [1] WHERE ...“