Lucas Ferraz
Lucas Ferraz

Reputation: 740

Mysql - Get Last inserted ID is not working


I dont know why this is not working. The LAST_INSERT_ID() is not being catched, can someone help me please?

$query = " 
            INSERT INTO products_categories ( 
                name,
                url
            ) VALUES ( 
                :name,
                :url
            ) SELECT LAST_INSERT_ID();
        "; 
        $query_params = array( 
            ':name' => $_POST['name'], 
            ':url' => $_POST['url']
        ); 
        try{ 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex){
            echo 0;
            return true;
        }
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        $id_category = $result["id"];

Upvotes: 0

Views: 80

Answers (2)

Prince Adeyemi
Prince Adeyemi

Reputation: 734

Try this;

<?php
$query = " 
            INSERT INTO products_categories ( 
                name,
                url
            ) VALUES ( 
                :name,
                :url
            )
        "; 
        $query_params = array( 
            ':name' => $_POST['name'], 
            ':url' => $_POST['url']
        ); 
        try{ 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex){
            echo 0;
            return true;
        }
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        //$id_category = $result["id"];
        $id_category = $db->lastInsertId();
        

Hope it helps

Upvotes: 1

Lucas Ferraz
Lucas Ferraz

Reputation: 740

"You can remove your SELECT LAST_INSERT_ID() part from the query and use $db->lastInsertId(); instead." - @barell

Upvotes: 1

Related Questions