How can I upload individual CSV rows into different tables in PHP?

限于喜欢 提交于 2020-07-31 05:53:13

问题


I'm trying to figure out the best way to do this. I have a database with 5 tables around 5 records/rows in MySQL and I need to update it frequently. The problem is the file I upload will be csv file. Also I want each lines to go into 5 different tables.,I'm trying to updated 'where' there is a unique id.

uid="001";

What is the best way to achieve this? I've been trying since morning, and I only know how to update one table alone at a time. Your suggestions is most appreciated. Thanks.

sample of csv and individual table below

csv sample:

   id           |     name     |   title    |
   -----------------------------------------------------
   1            |     james    | Chief      |
   2            |     job      | officer    |
   3            |     bats     | lawyer     |
   4            |     Supes    | thief      |
   5            |      WW20    | Lobster    |

table1:

uid    |     name     |   title   |
-----------------------------------
001    |              |           |
002    |              |           |
003    |              |           |

table2, table3 and table4 contains the data and field as table one

I want james and his title to go to table1, jobs and his title to table2, bats and his title to table3, e.t.c. all on row 001

About the uniquenes, the 'UID' in the database (each of the table) is the primary key..... and i want it to import it and update the tables using the uid as the location for each rows to enter the tables

Below is how i got the values in the csv, ignoring first line,which is the header alone.

$uid="001";
    if(isset($_POST["submit"]))
    {

        $file = $_FILES['file']['tmp_name'];
        $handle = fopen($file, "r");
        $c = 0;
        while(($filesop = fgetcsv($handle, 1000, ",")) !== false)
             {
            
            $name= $filesop[0];
            $title= $filesop[1]; 
}

$sql = "UPDATE eyfstb SET name='$name',title='$title'WHERE uid='$uid'";
            $stmt = mysqli_prepare($db,$sql);
            mysqli_stmt_execute($stmt);

             $c = $c + 1;
            }

             if($sql){
            echo "sucess";
            } 
             else
             {
             echo "Sorry! Unable to impo.";
            }

        }

回答1:


In your case, the best solution is the simplest one, so just creating five queries, you can even do it in the loop:

$pdo = new PDO("mysql:host=127.0.0.1;dbname=yourdbname;charset=utf8", "username", "password");

if (($handle = fopen("test.csv", "r")) !== FALSE) {
    $row = 1;
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if ($row == 1) {
            $row++;
            continue;
        }
        $row++;

        foreach (['table1', 'table2', 'table3', 'table4', 'table5'] as $table) {
            $stmt = $pdo->prepare("INSERT INTO $table (name, title) VALUES (?,?)");
            $stmt->execute([$data[0], $data[1]]);
        }
    }
    fclose($handle);
}

Or for UPDATE with uid replace the forech:

foreach (['table1', 'table2', 'table3', 'table4', 'table5'] as $table) {
    $stmt = $pdo->prepare("UPDATE $table SET name=?, title=? WHERE uid=?");
    $stmt->execute([$data[0], $data[1], $uid]);
}

Or even better with INSERT or UPDATE, note that in this case we're using named params.

foreach (['table1', 'table2', 'table3', 'table4', 'table5'] as $table) {
    $stmt = $pdo->prepare("INSERT INTO $table (uid, name, title) 
        VALUES (:uid, :name, :title) 
        ON DUPLICATE KEY UPDATE name=:name, title=:title");
    $stmt->bindValue('uid', $uid);
    $stmt->bindValue('name', $data[0]);
    $stmt->bindValue('title', $data[1]);
    $stmt->execute();
}

SQL for table1 .. table5

CREATE TABLE table1 (
 uid int(11) NOT NULL AUTO_INCREMENT,
 name varchar(255) NOT NULL,
 title varchar(255) NOT NULL,
 PRIMARY KEY (uid)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8

Note: When you'll describe better how do you want to maintain uniqueness I'll probably add some other solutions. At the moment code doesn't know if James, chief from CSV is the same James, chief in DB.



来源:https://stackoverflow.com/questions/63020487/how-can-i-upload-individual-csv-rows-into-different-tables-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!