根据某些条件一次将数组插入到两个表中

Insert into MySQL from array into two tables at once based on some conditions

提问人:Alex 提问时间:4/21/2022 更新时间:4/21/2022 访问量:80

问:

我有这个数组,其中包含来自 php 检查 https://github.com/shuchkin/simplexlsx 中与 SimpleXLSX 一起使用的 excel 文件中的数据行, 工作得很好,但问题是我希望所有数据都将它们插入到两个MySQL表中

在表 1 中没关系,但在表 2 中,这是问题所在,我想从表 1 中获取所有最后插入的 ID,并将它们插入表 2 中,其中包含 dansatori ID,如果您查看 [dansatori] 的 SimpleXLSX 输出,这是一个数组

请检查这张图片,看看我想实现什么: MySQL表

PHP 中的数组 SimpleXLSX 输出:

Array
(
    [0] => Array
        (
            [numecoregrafie] => Vampire Dance
            [niveldans] => 2
            [coregraf] => Damon Salvatore
            [sectiuni] => 1
            [disciplina] => 7
            [catvarsta] => 6
            [dansatori] => Array
                (
                    [0] => 84
                    [1] => 86
                )

            [nrdansatori] => 2
        )

    [1] => Array
        (
            [numecoregrafie] => End of the world
            [niveldans] => 1
            [coregraf] => Stephany
            [sectiuni] => 2
            [disciplina] => 14
            [catvarsta] => 4
            [dansatori] => Array
                (
                    [0] => 82
                    [1] => 87
                )

            [nrdansatori] => 2
        )

    [2] => Array
        (
            [numecoregrafie] => Slapping Chris Rock
            [niveldans] => 2
            [coregraf] => Will Smith
            [sectiuni] => 1
            [disciplina] => 13
            [catvarsta] => 18
            [dansatori] => Array
                (
                    [0] => 84
                )

            [nrdansatori] => 1
        )

)

到目前为止,我尝试过:

$file  = "MomenteMultiple_RDCP_2.xlsx";  // The excel file 
$xlsx  = new SimpleXLSX( $file );  // SimpleXLSX object

$dns       = array();
$skip      = 1; 
$dansatori = array();
$lastID    = array();

foreach ($xlsx->rows() as $key => $fields)
 { 
    if($skip !=1)   // Skipping the first row from XLSX file.
    {
      if($fields[7] > 0) {
         
        $rowValue   = !empty($fields) && $fields != "" ? $fields : 'null';   
        $result     = array_filter($rowValue);  // remove empty values from array
        $values     = explode(",",  $result[6]);  // explode string into array
        $dancersIDS = array_filter($values);  
        
        $dns[] = [
            'numecoregrafie' => $result[0],
            'niveldans'      => $result[1],
            'coregraf'       => $result[2],
            'sectiuni'       => $result[3],
            'disciplina'     => $result[4],
            'catvarsta'      => $result[5],
            'dansatori'      => $dancersIDS,
            'nrdansatori'    => $result[7],
            'uid'            => $user->filter->id
        ];   // Add the values to the array
      }   
    }
    $skip++;  // Increment the skip value
 }
 
// Table 1
 $query = 
 'INSERT INTO `rdcp_momente` 
  (numecoregrafie, 
   niveldans, 
   coregraf, 
   sectiuni, 
   disciplina, 
   catvarsta, 
   nrdansatori
   ) VALUES';   // Query to insert values into table 1
  
  // Table 2
 $queryd = 
 'INSERT INTO `rdcp_dansatorim` 
  (`did`, 
  `uid`,
   `mid`
  ) VALUES';   // Query to insert values into table 2
  
  foreach($dns as $d) { 
      $query .= "
      (
        '".$d['numecoregrafie']."', 
        '".$d['niveldans']."', 
        '".$d['coregraf']."', 
        '".$d['sectiuni']."', 
        '".$d['disciplina']."', 
        '".$d['catvarsta']."', 
        '".$d['nrdansatori']."'
      ),"; // Query to insert values into table 1
      foreach($d['dansatori'] as $dansator) 
      { 
        $queryd .= "
        (
          '".$dansator."', 
          '".$user->filter->id."', 
          '".$lastID."'
        ),"; // LastID is the last inserted id of the table 1
      } 
  } 
  
  $query  = rtrim($query, ",");  // remove last comma
  $queryd = rtrim($queryd, ","); 
  $query .= ";";  
  $queryd .= ";"; 
  $db->query($query);  // insert into table 1 
  $lastID[] = $db->insertId(); // get the last inserted id
  $db->query($queryd); // insert into table 2
   
    echo '<pre>';  
    echo var_dump($query);    
    echo '<pre>';  
    echo var_dump($queryd);

仅插入一个 ID,而不是与上次插入的行对应的所有 ID

php mysql 数组 mysqli

评论

1赞 Phil 4/21/2022
警告:您对 SQL 注入持开放态度,并且应该真正使用参数化的预准备语句,而不是手动构建查询。它们由 PDOMySQLi 提供。永远不要相信任何类型的输入,尤其是来自客户端的输入。逃避是不够的

答:

3赞 Phil 4/21/2022 #1
  1. 准备你的陈述INSERT
  2. 绑定参数
  3. 循环访问数据
    1. 执行您的第一个语句
    2. 获取最后一个插入 ID
    3. 循环访问索引dansatori
      1. 执行第二条语句

由于采用变量引用,因此可以在开始迭代数据之前准备和绑定参数。mysqli_stmt::bind_param

$stmt1 = $db->prepare('INSERT INTO `rdcp_momente` (numecoregrafie, niveldans, coregraf, sectiuni, disciplina, catvarsta, nrdansatori) VALUES (?, ?, ?, ?, ?, ?, ?)');
// you might want to tweak the parameter types
$stmt1->bind_param('sssssss',
    $d['numecoregrafie'], 
    $d['niveldans'], 
    $d['coregraf'], 
    $d['sectiuni'], 
    $d['disciplina'], 
    $d['catvarsta'], 
    $d['nrdansatori']);

$stmt2 = $db->prepare('INSERT INTO `rdcp_dansatorim` (`did`, `uid`, `mid`) VALUES (?, ?, ?)');
$stmt2->bind_param('ssi', $dansator, $user->filter->id, $lastId);

foreach ($dns as $d) {
    $stmt1->execute();
    $lastId = $db->insert_id;
    foreach($d['dansatori'] as $dansator) {
        $stmt2->execute();
    }
}