如何将 CSV 文件中的不同行放入表中?

我想将我的 csv 上传文件的第 1 行放入表 tab1........ 并将第 2 行放入表 tab2


我努力了:


$myid = 231;

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

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

    if (($handle = fopen($file, "r")) !== FALSE) {

        $row = 0;

        while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {

            if ($row == 1) {

                $row++;

                continue;

            }

            $row++;

            foreach (['tab1', 'tab2'] as $table) {

                $stmt = $pdo->prepare("UPDATE $table SET fname=?, lname=? WHERE id=?");

                $stmt->execute([$data[0], $data[1], $myid]);

            }

        }

        fclose($handle);

    }

}


幕布斯6054654
浏览 99回答 1
1回答

千巷猫影

问题是因为要插入到表中的 foreach 循环每次在 while 循环周围都会插入到两个表中。仅当 $row==1 且 tab2 为 $row==2 时才插入 tab1。试试这个(未经测试):$myid = 231;if (isset($_POST["submit"])) {&nbsp; &nbsp; $file = $_FILES['file']['tmp_name'];&nbsp; &nbsp; if (($handle = fopen($file, "r")) !== FALSE) {&nbsp; &nbsp; &nbsp; &nbsp; $row = 0;&nbsp; &nbsp; &nbsp; &nbsp; $tables = ['tab1', 'tab2'];&nbsp; &nbsp; &nbsp; &nbsp; while (($data = fgetcsv($handle)) !== FALSE && $row<3) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ($row > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $stmt = $pdo->prepare("UPDATE ".$tables[$row-1]." SET fname=?, lname=? WHERE id=?");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $stmt->execute([$data[0], $data[1], $myid]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $row++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fclose($handle);&nbsp; &nbsp; }}我创建了两个表的数组,然后根据行号更新相关表。当我们达到 2 行时,我还添加了一个中断,以防 CSV 的行数超出您的预期。
打开App,查看更多内容
随时随地看视频慕课网APP