mysql 如何将数据加载到多个表SQL

xj3cbfub  于 2022-11-28  发布在  Mysql
关注(0)|答案(2)|浏览(120)

下面是我的脚本导入数据到mysql:

foreach ($file_data as $row) {
    
    $sku = $row[$_POST["sku"]];
    $title = $row[$_POST["title"]];
    $slug = $row[$_POST["title"]];
    $product_type = "physical";
    $description = $row[$_POST["description"]];
}
   if(isset($sku))
 {
  $query = "
  INSERT INTO products
  (sku, slug, product_type) 
  VALUES ".implode(",", $sku).",".implode(",", $slug).",".implode(",", $product_type)."
  ";

  $statement = $connect->prepare($query);

  if($statement->execute())
  {
   echo 'Data Imported Successfully';
  }
 }

现在有人能帮我把$title$description加载到第二个表product_details吗?
@更新@梅尔沃兹

foreach ($file_data as $row) {
    
    $sku = $row[$_POST["sku"]];
    $title = $row[$_POST["title"]];
    $slug = $row[$_POST["slug"]];
    $product_type = "physical";
    $description = $row[$_POST["description"]];
    
 if (isset($sku)) {
        $statement = $connect->prepare("INSERT INTO products
         (sku, slug, product_type) 
         VALUES '$sku','$slug','$product_type'");
       $statement2 = $connect->prepare("INSERT INTO product_details
         (title, description) 
         VALUES '$title','$description'");
   
   
        if (!$statement->execute()) {
            $error = 'None or part of the data was updated';
        }
    }
}
echo $error ?? 'Data Updated Successfully';
7d7tgy0s

7d7tgy0s1#

也许你可以推任何数组

<?php

$query_array = [];


foreach ($file_data as $row) {
    
    $sku = $row[$_POST["sku"]];
    $title = $row[$_POST["title"]];
    $slug = $row[$_POST["title"]];
    $product_type = "physical";
    $description = $row[$_POST["description"]];

    if(isset($sku)){

        $query = 'INSERT INTO products
        (sku, slug, product_type) 
        VALUES SET title="'.$title.',sku="'.$sku.'", etc.. #add more"';

        $query = rtrim($query,',');
        array_push($query_array,$query);

    }



}

foreach ($query_array as $key => $value) {
    $mysqlconn->query($value);
}
gdrx4gfi

gdrx4gfi2#

这可能对你有用。

$T1Values = "";
$T2Values = "";

foreach ($file_data as $row) {
    $T1Values .= "('" . $row[$_POST['sku']] . "','" . $row[$_POST['slug']] . ",'" . $row[$_POST['product_type']] . "),";
    $T2Values .= "('" . $row[$_POST['title']] . "','" . $row[$_POST['description']] . "'),";
}
if (isset($sku)) {

    $T1Values = trim(',', $T1Values);
    $T2Values = trim(',', $T2Values);

    $query1 = "INSERT INTO products (sku, slug, product_type) VALUES($T1Values)";

    $statement = $connect->prepare($query1);

    if ($statement->execute()) {
        $query2 = "INSERT INTO product_details (title, product_details) VALUES($T2Values)";
        $statement = $connect->prepare($query2);
        if ($statement->execute()) {
            echo "All records inserted successfully";
        }
    }
}

相关问题