小编典典

SQL INSERT INTO多个表

sql

如何查询这两个?我将数据插入两个表中。

 $query = "
              INSERT INTO dc_mail_users (
                  i_id_pk, c_user, c_passwd_md5, i_user_active_id_fk, i_user_type_id_fk
              ) VALUES (
                  %1%, %2%, %3%, %4%, %5%
              )";

 $query2 = "
              INSERT INTO dc_mail_user_data (
                   i_id_ut, c_user_sex, c_user_name, c_user_surname, c_user_url
              ) VALUES (
                  %1%, %2%, %3%, %4%, %5%
              )";

阅读 429

收藏
2021-04-14

共1个答案

小编典典

目的是什么?您是否要从一种HTML表单将数据插入到两个不同的表中?我不知道存储过程,但是我在类似的情况下使用事务:

$d = dbSingle::dbLink();
//set autocommit to false
mysqli_autocommit($d->getDbc(), FALSE);

$query = " INSERT INTO dc_mail_users (
              i_id_pk, c_user, c_passwd_md5, i_user_active_id_fk, i_user_type_id_fk
          ) VALUES (
              %1%, %2%, %3%, %4%, %5%
          )";

$r = $d->sqlQ($query);

//get the last inserted id for the second query
$last_insert_id = $d->getInsertId();

$query2 = "
          INSERT INTO dc_mail_user_data (
               i_id_ut, c_user_sex, c_user_name, c_user_surname, c_user_url
          ) VALUES (
              %{$last_insert_id}%, %2%, %3%, %4%, %5% //not sure about the syntax, sorry
          )";


$r2 = $d->sqlQ($query2);

//rollback if either one of the queries failed
if (!$r || (isset($r2) && !$r2)) {
  mysqli_rollback($d->getDbc());
}
  else  {
    //commit if everything worked
    mysqli_commit($d->getDbc());

  //autocommit on
  mysqli_autocommit($d->getDbc(), TRUE);
  }

假设i_id_ut在表中dc_mail_user_data是FK,并且i_id_pk是自动递增字段。我有一个名为dbSingle的类,其中包含查询功能和数据库连接。希望它足够清晰,可以与常规mysqli函数一起使用。

2021-04-14