2

我有 3 个表:用户、学生、学生详细信息

用户的主键是表student(userid)中某个字段的外键,学生的主键是表studentdetails(studentid)中某个字段的外键。

我需要在一次提交中将数据从一个表单插入到所有 3 个表中,以下是 SQL 脚本:

    $sql = "

    INSERT INTO `tbluser`(`username`, `password`, `roleid`, `datecreated`)
    VALUES ('$email','$password', '$role', CURRENT_TIMESTAMP);

    SELECT @uid := MAX(`userid`) FROM `tbluser`;

    INSERT INTO `tblstudent` (`userid`, `scholarnumber`, `firstname`, `middlename`,
    `lastname`, `datecreated`)
    VALUES ('@uid', '$scholar_no', '$first_name', '$middle_name', '$last_name',
    CURRENT_TIMESTAMP);


    SELECT @stuID :=  MAX(`studentid`) FROM `tblstudent`;

    INSERT INTO `tblstudentdetails` (`studentid`,`dob`, `studenttype`, `gender`,
    `religion`, `category`, `currentsuburbid`,   `currentcityid`, `currentaddress1`,
    `currentzipcode`, `currentstateid`,  `currentcountryid`,`mobile`,`phone1`,`email1`,
    `passportnum`, `permasuburbid`,  `permaaddress1`, `dateofjoining`,
    `admissionreferenceof`, `datecreated`, `dateupdated`) 

    VALUES ('@stuid', '$dob' ,'$studenttype' ,'$gender','$religion','$category',
    '$currentsuburbid', ' $currentcityid', '$currentaddress1', '$currentzipcode',
    '$currentstateid', '$currentcountryid', '$mobile',
    '$phone1','$email1','$passportnum','$permanentsuburbid', '$permanentaddress1',
    '$doj', ' $admissionreference',current_timestamp, current_timestamp);

    ";

我无法找出问题所在,上面的脚本在 mysql (phpmyadmin) 中工作,但在 php 中它不起作用。我了解,我需要使用我的 multi_query (??),但它不会给出任何错误并在两个表中插入,但不会在第三个表中。我觉得这可能与两者之间的 SELECT 语句有关?在这里斗智斗勇,我将不胜感激任何帮助。提前致谢。

4

1 回答 1

1

看起来您正在尝试从 mysqli 运行多个用分号分隔的 SQL 语句。那是行不通的。您需要分别发出每个不同的语句。

您可以使用 MySQL 的事务(只要您对表使用 InnoDB 或其他一些访问方法,而不是MyISAM:MyISAM 不处理事务)。

你可以这样做:

$connection->begin_transaction();
/* issue your statements one by one */
$connection->commit();

这将导致您的所有插入物等同时变得可见。

但是:您正在尝试使用您最近的自动增量 ID 号。你这样做是错误的。您需要使用 MySQL 的LAST_INSERT_ID()功能来代替您的

SELECT @uid := MAX(`userid`) FROM `tbluser`;   /*wrong*/

图案。这是有效的,因为LAST_INSERT_ID()从您的第一个插入提供了 ID 的值,因此第二个插入将使用它。即使多个程序向表中插入内容也是安全的,因为 MySQL 为每个程序连接保留一个单独的值。它比您拥有的更快,因为它不必查看表格,并在使用它之前将值返回给您的程序。

所以这样做,你会得到你想要的。

/* do the first insert, using an autoincrementing uid column */
INSERT INTO `tbluser`(whatever, whatever, whatever)
              VALUES (whatever, whatever, whatever);
/* now LAST_INSERT_ID() contains the value inserted into tbluser.uid */

/* do the second insert, using the id from the first insert into tblstudent.userid */
INSERT INTO `tblstudent` (`userid`,         whatever, whatever, whatever)
                  VALUES (LAST_INSERT_ID(), whatever, whatever, whatever);
/* now LAST_INSERT_ID() contains the value inserted into tblstudend.studentid */

/* use that value to insert into tblstudentdetails.studentid */
INSERT INTO `tblstudentdetails` (`studentid`,      whatever, whatever, whatever) 
                         VALUES (LAST_INSERT_ID(), whatever, whatever, whatever);
于 2014-09-19T12:24:05.417 回答