首页 > 解决方案 > 如何在 PHP 中使用 SQL 或 PDO 获取最后插入的 id?

问题描述

大家好,也许有人可以帮助我找到从我的数据库中获取最后插入的 ID 的方法......我仍在努力学习。

一定有错误,但我不知道在哪里:/

这是我的 php 代码。数据被发送到我的数据库并保存,但我不知道如何取回用户 ID。它是我的用户表中的主键,并在 mysql 数据库中设置为自动增量。

我希望有人知道如何提供帮助:D 谢谢

php代码:

**
<php 
$host = 'localhost';
        $name = 'datatry';
        $user = 'datatry';
        $passwort = 'data';
        
        try{
                $mysql = new PDO("mysql:host=localhost;dbname=datatry", "datatry", "hello");
            }
        catch(PDOException $e){
            echo "SQL Error: ".$e->getMessage();
    
        }
        if(isset($_POST["submit"])){
            
            echo"Your UserId";
            
            $statement = $mysql ->prepare ('INSERT INTO User (Name, Street, Birthdate, Code,  Email, Password) VALUES (:Name, :Street, :Birthdate, :code, :Email, :Password)');
            $statement->bindParam("Name", $_POST["Name"]);
            $statement->bindParam("Nachname", $_POST["Street"]);
            $statement->bindParam("Geburtstag", $_POST["Birthdate"]);
            $statement->bindParam("PLZ", $_POST["Code"]);
            $statement->bindParam("Email", $_POST["Email"]);
            $statement->bindParam("Passwort", $_POST["Password"]);
            
            $id = $mysql ->lastInsertId();
            $statement = $mysql->query("SELECT LAST_INSERT_ID()");
            $lastId = ♡statement->fetchColumn();
            
            
            $statement-> execute ();
            
            if(!$statement){
                print_r($mysql->errorInfo());
            }
        }
        
?>

**

标签: phpmysqlsqldatabase

解决方案


推荐阅读