简体   繁体   English

使用php在不同的sql表中导入csv文件的选定列

[英]importing selected columns of csv file in different sql tables using php

My csv file looks like this:我的 csv 文件如下所示:

Name | DateOfBirth| Gender| Occupation| DateOfTest | FieldNumber | Eye | ThresholdValue

Fred, 12/08/68,M, carpenter, 12/02/06, 1, R, 1234
Susan, 3/09/72, F, hairstylist, 12/04/07, 1, R, 1234
Fred, 12/08/68,M, carpenter, 12/02/06, 1, L, 1234
Susan, 3/09/72, F, hairstylist, 12/04/07, 1, L, 1234
Fred, 12/08/68,M, carpenter, 12/02/08, 1, R, 1234
Susan, 3/09/72, F, hairstylist, 12/04/08, 1, R, 1234
Fred, 12/08/68,M, carpenter, 12/02/08, 1, L, 1234
Susan, 3/09/72, F, hairstylist, 12/04/08, 1, L, 1234

Each patient will have two rows(for left and right eye) for each instance of test undertaken by them and they can undertake multiple tests.每个患者将有两行(左眼和右眼)用于他们进行的每个测试实例,并且他们可以进行多个测试。 I have to put this information in a database in a way that it can be extracted from different dimensions like analyse data from all females, or analyse data from all carpenters etc. I thought of following two tables:我必须将这些信息以一种可以从不同维度提取的方式放入数据库中,例如分析所有女性的数据,或分析所有木匠的数据等。我想到了以下两个表:

Patient_info
PatientID(auto-increment primary key), name, dob, gender, occupation 

test_info
testID(auto-increment primary key), patientID(foreign key from patient_info), dot, fieldnumber, eye, thresholdvalue 

I have been able to populate patient_info table by using fgetcsv() function of php.我已经能够通过使用 php 的 fgetcsv() 函数来填充patient_info表。 $sql works fine but $sql2 does not. $sql 工作正常,但 $sql2 不行。

<?php



    ini_set("auto_detect_line_endings", true);
    include "connection.php";

    $deleterecords = "TRUNCATE TABLE patient_info";
    mysql_query($deleterecords);

    $deleterecords = "TRUNCATE TABLE test_info";
    mysql_query($deleterecords);    

    if(isset($_POST['submit']))
    {

        $file = $_FILES['file']['tmp_name'];

        $handle = fopen($file,"r");

        while(($fileop = fgetcsv($handle, 1000, ",")) !== false)
        {
            $name = $fileop[0];
            $dateofbirth = $fileop[1];
            $gender = $fileop[2];
            $occupation = $fileop[3];
            $dateoftest = $fileop[4];
            $field = $fileop[5];
            $eye = $fileop[6];
            $thresholdvalues = $fileop[7];
            $sql = mysql_query("INSERT INTO patient_info (Name, DateOfBirth, Gender, Occupation) VALUES ('$name','$dateofbirth','$gender','$occupation')" );
            $sql2 = mysql_query("INSERT INTO test_info (DateOfTest, FieldNumber, Eye, ThresholdValues) VALUES   ('$dateoftest','$field','$eye','$thresholdvalues')" );

        }
            fclose($handle);
            if($sql2) { echo 'test data successfully uploaded';}

            if($sql) 
            {
                echo 'Data uploaded successfully';
                header("Location: http://localhost/lei/test.com/proper/upload_page.php");
                exit();
            }
            else
            {
                echo 'Upload Failed';
            }

    }

?>

Questions: 1) How can I insert just one record for each patient in patient_info table, but multiple records for each instance of test undertaken by the patient in test_info table??问题:1)如何在患者信息表中为每位患者仅插入一条记录,但如何在 test_info 表中为患者进行的每个测试实例插入多条记录? 2) How should I populate test_info table using patientID from patient_info table and other values from csv file? 2)我应该如何使用patient_info表中的patientID和csv文件中的其他值填充test_info表? 3) I want to empty both the tables every time a new csv file is uploaded. 3) 每次上传新的 csv 文件时,我都想清空这两个表。 I was using TRUNCATE query to do that, but since I defined PatientID as foreign key, TRUNCATE does not work.我使用 TRUNCATE 查询来做到这一点,但由于我将 PatientID 定义为外键,因此 TRUNCATE 不起作用。 How can I empty both the tables before uploading a new csv file?如何在上传新的 csv 文件之前清空两个表?

Thanks in advance !提前致谢 !

Why use PHP for this at all?为什么要为此使用 PHP? I'd do it all natively within SQL:我会在 SQL 中本地完成所有操作:

  1. Define your tables (if not already done).定义您的表格(如果尚未完成)。 Note that you must define a uniqueness constraint over the relevant columns in patient_info by which you will identify matching patients from your CSV data:请注意,您必须在patient_info的相关列上定义唯一性约束,您将从 CSV 数据中识别匹配的患者:

     CREATE TABLE patient_info ( PatientID SERIAL, Name VARCHAR(255), DateOfBirth DATE, Gender ENUM('M','F'), Occupation VARCHAR(255), UNIQUE(Name, DateOfBirth, Gender, Occupation) ); CREATE TABLE test_info ( TestID SERIAL, PatientID BIGINT UNSIGNED, DateOfTest DATE, FieldNumber INT UNSIGNED, Eye ENUM('R','L'), ThresholdValue INT UNSIGNED, FOREIGN KEY (PatientID) REFERENCES patient_info (PatientID) );
  2. Define a table into which you will import the raw CSV data:定义一个表,您将在其中导入原始 CSV 数据:

     CREATE TABLE import ( Name VARCHAR(255), DateOfBirth DATE, Gender ENUM('M','F'), Occupation VARCHAR(255), DateOfTest DATE, FieldNumber INT UNSIGNED, Eye ENUM('R','L'), ThresholdValue INT UNSIGNED );
  3. Define an AFTER INSERT trigger that will split the imported data and perform the relevant insertions into your "real" tables.定义一个AFTER INSERT触发器,它将拆分导入的数据并执行相关插入到您的“真实”表中。 You can use INSERT ... ON DUPLICATE KEY UPDATE together with LAST_INSERT_ID() to obtain the PatientID of each record, even if it already exists:您可以将INSERT ... ON DUPLICATE KEY UPDATELAST_INSERT_ID()一起使用来获取每条记录的PatientID ,即使它已经存在:

     DELIMITER // CREATE TRIGGER trig AFTER INSERT ON import FOR EACH ROW BEGIN INSERT INTO patient_info ( Name, DateOfBirth, Gender, Occupation ) VALUES ( NEW.Name, NEW.DateOfBirth, NEW.Gender, NEW.Occupation ) ON DUPLICATE KEY UPDATE PatientID = LAST_INSERT_ID(PatientID) ; INSERT INTO test_info ( PatientID, DateOfTest, FieldNumber, Eye, ThresholdValue ) VALUES ( LAST_INSERT_ID(), NEW.DateOfTest, NEW.FieldNumber, NEW.Eye, NEW.ThresholdValue ); END// DELIMITER ;
  4. Import the data:导入数据:

     LOAD DATA INFILE '/path/to/file.csv' INTO TABLE import FIELDS TERMINATED BY ',' ;
  5. Tidy up:整理:

     DROP TRIGGER trig; DROP TABLE import;

    Or alternatively (depending on whether you intend to reuse it in the future):或者(取决于您将来是否打算重用它):

     TRUNCATE import;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM