返回最后插入SQL的值的ID

时间:2016-05-07 12:23:40

标签: php mysql

我将数据插入到成员表中,在插入之后我想获取刚刚插入的信息的userID。这样做最好的方法是什么?

我的PHP代码

    //Insert info into database
    $sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')";

        //Run a query to check if data has been inserted correctly.
        $records = mysqli_query($connect, $sql);

我确实尝试过这个SQL,但却遇到了错误

    $sql = "INSERT INTO members (type, firstname, lastname, email, password, bio) VALUES ('$usertype', '$firstname', '$lastname', '$emailsighup', '$passwordsighnup', '$bio')"; SELECT SCOPE_IDENTITY(userID);

1 个答案:

答案 0 :(得分:2)

假设$connect作为保存您的连接信息的变量,这似乎是合法的,您可以通过以下方式获取最后一个ID的值:

$user_id = mysqli_insert_id($connect);

您可以从PHP MySQLi interface执行此操作,而不是直接从SQL执行此操作!