简体   繁体   中英

Get auto increment id mysql

How can I get the automatically incremented user id of the mysql query. I tried it with mysql_insert_id() but it wont work.

    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();
        }
}
?>

You are using mysqli not mysql .

try $id = $mysqli->insert_id; after query not before.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM