在一个事务mysqli php5中多次插入

时间:2014-09-19 11:58:57

标签: mysql php-5.5 mysqli-multi-query

我有3张桌子: 用户,学生,学生细节

用户的主键是表student(userid)中字段的外键,student的主键是table 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语句有关吗?在这里结束时,我将非常感谢任何帮助。谢谢你提前。

1 个答案:

答案 0 :(得分: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);