php MySQL lastInsertID

时间:2015-03-08 18:44:50

标签: php mysql

有人知道为什么我用这段代码得到0的返回值:

        /* check connection */
        if (mysqli_connect_errno()) {
            error_log("Connect failed: " . mysqli_connect_error());
            echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
        } else {
            $stmt = $mysqli->prepare("INSERT INTO teams (name, token) VALUES (?, ?)");
            $stmt->bind_param('ss', $team, $token);


            /* execute prepared statement */
            $stmt->execute();

            if ($stmt->error) {error_log("Error: " . $stmt->error); }

            $success = $stmt->affected_rows;

            //Get the last insert ID of the insert Team
            $lastInsertID = $stmt->insert_id;




                //Insert into the Mapping Table
                $stmt = $mysqli->prepare("INSERT INTO usersTeamsMap (users_idUser, teams_idTeam) VALUES (?, ?)");
                $stmt->bind_param('ii', $userID , $lastInsertID );


                /* execute prepared statement */
                $stmt->execute();

                //Get the last insert ID of the insert Team
                $lastInsertID = $stmt->insert_id;
                echo "ID: " . $lastInsertID;

最后一个echo总是返回0.第一个“$ lastInsertID = $ stmt-> insert_id;”第一个插入查询的工作正常。

提前致谢。

编辑:

感谢所有答案。现在我知道为什么服务没有用。我的映射表没有AutoIncrement字段。

1 个答案:

答案 0 :(得分:0)

insert_id是mysqli对象的属性,而不是语句的属性!它是特定于连接的。

所以它应该是$mysqli->insert_id