0

Hello everyone maybe someone can help me find a way to get the last inserted Id from my database ... I am still trying to learn.

There must be a mistake but i do not know where :/

This is my php Code. The data is send to my database and saved but I don't know how to get back the Userid. It is the Primary key from my table User and set on auto increment in a mysql database.

I hope someone knows how to help :D Thank you

Php Code:

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

**

Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
Lion
  • 1
  • 1
  • You need to do the `$statement-> execute ();` before the last insert ID is available. – Nigel Ren Feb 05 '21 at 17:11
  • You need to executive the first query, the one that you are performing the bindings for ... then once that is done, you can get the lastInsertedID ... the second query is not needed and should not be used...you can not stack queries in mysql, 1 at a time – Ryan H Feb 05 '21 at 17:50

0 Answers0