How to get the last id inserted in mysql using OOP PHP?

I have the following PHP class, I use it to connect to db and create a new instance:

class db{

    public $db_connection;

    public function __construct(){

        $this->db_connection = new mysqli("127.0.0.1","user","passwd","table");
        $this->db_connection->set_charset("utf8");

        if($this->db_connection->connect_errno) {
            echo "Failed to connect to database: " . $db_connection->connect_error;
        }
    }

    public function __destruct(){
        return $this->db_connection->close();
    }
}

The im code used to add material to the database:

$db = new db();

$success = $db->db_connection->query(
    "INSERT INTO users(
        name
    )
    VALUES(
        '".$_POST["firstname"].'
    )"
);

Get the id of the inserted aboue element:

if($success){
    $user_id = $db->db_connection->insert_id;
    echo $user_id; // outputs 0
}

I get a value of 0, even if I have several records in the database, is there any other way? Identifier also has AUTO INCREMENT in the table.

Note. The code is simple, not the whole structure, but enough to explain the real issiue.

+4
source share
1 answer

INSERT ? , . - , , .

if ($db->db_connection->query($insert)) {
   $user_id=$db->db_connection->insert_id;
} else {
   // add some error handling/logging
}
+1

All Articles