获取自动增量id mysql

时间:2015-03-22 11:54:08

标签: php mysql

如何获取mysql查询的自动递增用户ID。我用mysql_insert_id()试了一下,但它不起作用。

    if(isset($_COOKIE['username'])){
    $cookie = $_COOKIE['username'];
    header('Location: http://' . $_SERVER['HTTP_HOST'] . '/source/main.html');
}
else{
    $message = array();
    if (!empty($_POST)) {
        if (
            empty($_POST['f']['username'])

        ) {
            $message['error'] = 'Es wurden nicht alle Felder ausgefüllt.';
        } 
        $mysqli = @new mysqli('localhost', 'user', 'pw', 'loginsystem');
            if ($mysqli->connect_error) {
                $message['error'] = 'Datenbankverbindung fehlgeschlagen: ' . $mysqli->connect_error;
            }
            $query = sprintf(
                "INSERT INTO users (username)
                SELECT * FROM (SELECT '%s') as new_user
                WHERE NOT EXISTS (
                    SELECT username FROM users WHERE username = '%s'
                ) LIMIT 1;",
                $mysqli->real_escape_string($_POST['f']['username']),

                $mysqli->real_escape_string($_POST['f']['username'])

            );
            $id = mysql_insert_id();

            $mysqli->query($query);
            if ($mysqli->affected_rows == 1) {
                $message['success'] = 'Neuer Benutzer (' . htmlspecialchars($_POST['f']['username']) . ') wurde angelegt, <a href="login.php">weiter zur Anmeldung</a>.';
                header('Location: http://' . $_SERVER['HTTP_HOST'] . '/source/main.html');
            } else {

            }
            $t = time() + 60; //* 60 * 24 * 1000;
            setcookie("username", $_POST['f']['username'], $t);
            setcookie("userid", $id , $t);
            // cookie setzen
            $mysqli->close();
        }
}
?>

1 个答案:

答案 0 :(得分:0)

您使用的是mysqli而不是mysql

在查询之后尝试$id = $mysqli->insert_id;