简体   繁体   English

mysql 插入两个表

[英]mysql insert in two tables

I am trying to make a register form where you can register your organisation and account at the same time.我正在尝试制作一个注册表,您可以在其中同时注册您的组织和帐户。 But at the moment I do not know how to insert the data correctly.但目前我不知道如何正确插入数据。 Because if you want to insert the user in the table you do not know the organisation_id yet...因为如果您想在表中插入用户,您还不知道组织 ID...

I have tried using mysqli_insert_id($conn) to get the last inserted id but that is not really practical.我曾尝试使用mysqli_insert_id($conn)来获取最后插入的 id 但这并不实用。

I also came to the problem that if the email of the user already existed that it would still register the organisation.我还遇到了一个问题,如果用户的电子邮件已经存在,它仍然会注册该组织。

At this moment I am completely lost...这一刻我彻底迷失了……

Here is a sample of my table structure with some dummy data:这是我的表结构示例,其中包含一些虚拟数据:


organisations table组织表

+-----------------+--------------------+
| organisation_id | organisation_name  |
+-----------------+--------------------+
|               1 | Google             |
|               2 | Facebook           |
+-----------------+--------------------+

users table用户表

+---------+------------------+----------+-----------------+
| user_id |      email       | password | organisation_id |
+---------+------------------+----------+-----------------+
|       1 | test@gmail.com   | *****    |       1         | 
|       2 | test@outlook.com | ******   |       2         |
+---------+------------------+----------+-----------------+
         //check for existing emails for user in database
        $get_email_stmt = $conn->prepare('SELECT `email` FROM `users` WHERE email = ?');
        $get_email_stmt->bind_param('s', $user_email);
        $get_email_stmt->execute();
        $get_email_result = $get_email_stmt->get_result();
        $row = $get_email_result->fetch_assoc();
        //if email does not exists execute query
        if ($row['email'] == $user_email) {
           //give error email exists
           $_SESSION["exists"] = "email";
           header('Location: ../register');
        }

        //check for existing organisation name for user in database
        $get_organisation_stmt = $conn->prepare('SELECT `organisation_name` FROM `organisations` WHERE organisation_name = ?');
        $get_organisation_stmt->bind_param('s', $organisation_name);
        $get_organisation_stmt->execute();
        $get_organisation_result = $get_organisation_stmt->get_result();
        $row = $get_organisation_result->fetch_assoc();
        //if email does not exists execute query
        if ($row['organisation_name'] == $organisation_name) {
           //give error email exists
           $_SESSION["exists"] = "organisation";
           header('Location: ../register');
        }

        //insert organisation
        $post_organisation_stmt = $conn->prepare('INSERT INTO `organisations` (organisation_name, zipcode, cityname, country, organisation_phonenumber, organisation_email, organisation_type, organisation_url, organisation_vat, agreed_to_avg) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?);');
        $post_organisation_stmt->bind_param('sssssssssi', $organisation_name, $zipcode, $cityname, $country, $organisation_phonenumber, $organisation_email, $request, $organisation_url, $organisation_vat, $agreed_to_avg);

        //execute query
        if ($post_organisation_stmt->execute()) {
            $organistation_id = mysql_insert_id($conn);
            $post_organisation_stmt->close();
            //insert user
            $post_user_stmt = $conn->prepare('INSERT INTO `users` (firstname, lastname, email, phonenumber, organisation_id, hpassword, permission, agreed_to_avg) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?);');
            $post_user_stmt->bind_param('sssssssi', $firstname, $lastname, $user_email, $user_phonenumber, $organisation_id, $hPassword, $permission, $agreed_to_avg);
            //execute query
            if ($post_user_stmt->execute()) {
                //succes
                $post_answer_stmt->close();
                $_SESSION["newaccount"] = "success";
                header('Location: ../login');
            } else {
                //error
                echo "Error updating record: " . mysqli_error($conn);
                $post_answer_stmt->close();
                $_SESSION["exists"] = "error";
                header('Location: ../register');
            }
        } 

It seems that the problem you are describing is this:您描述的问题似乎是这样的:

  1. INSERT INTO organisation插入组织
  2. Get inserted organisation id获取插入的组织 ID
  3. INSERT INTO user插入用户
  4. If email already exists, then no user is created but the organisation remains in the database.如果电子邮件已存在,则不会创建用户,但组织仍保留在数据库中。

This can be resolved by using a transaction, see https://www.php.net/manual/en/mysqli.begin-transaction.php if using mysqli.这可以通过使用事务来解决,如果使用 mysqli,请参阅https://www.php.net/manual/en/mysqli.begin-transaction.php

When you run both queries in a transaction, then all changes can be rolled back when an exception occurs such as a unique constraint violation for the user email.当您在一个事务中运行这两个查询时,当发生异常(例如用户电子邮件的唯一约束冲突)时,所有更改都可以回滚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM