sdfgg45
sdfgg45

Reputation: 1242

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

I have the following PHP class, im using this to connect to db and make 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 code im using to add stuff to the database:

$db = new db();

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

Get the ID of the inserted element aboue:

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

I am getting the value 0 even tho i have several entries in the database, is there another way around this? The id also have AUTO INCREMENT on the table

Note: Code is simplefied, and not the whole structure, but enough to explain the real issiue.

Upvotes: 4

Views: 3206

Answers (1)

symcbean
symcbean

Reputation: 48357

Why are you separating the INSERT from polling the insert id? In both cases a failure means you haven't added a row. If you do anything else with the database link in between you'll run into complications which may be what is happening here.

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

Upvotes: 1

Related Questions