I made a class to connect with database but now I have run into a little problem. I need to get the id of last inserted row, but I dont know how to accomplish it.

Here is my connection class:


class Connection{
    public function __construct($config){
        $this->mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['db']);
            die("Connection error: " . mysqli_connect_errno());

    public function query($sql){
        $this->result = $this->mysqli->query($sql);
        if($this->result == true){
            return true;
            die("<strong>There was a problem with the query: </strong> " . $sql);

    public function get(){
        $data = array();

        while ($row = $this->result->fetch_array(MYSQLI_ASSOC)){ //MYSQLI_NUM numbritega jarjestamiseks
            $data[] = $row;

        return $data;

    public function __destruct(){

As you can see I use the same function for selecting and insering but select doesnt return lastInsertId. Please help me modify this class so I can get the row id when I insert data.

4 Years
Discussion Span
Last Post by Martin C++
public function getLastInsertId()
    // you can do checks first (has the query been successful etc)

    return $this->mysqli->insert_id;

It would be good idea to initialize the properties:

protected $mysqli = null;
protected $result = null;

I would also use more descriptive names. The connection class is not only doing the connection, it is also returning the data. $mysqli property would be better named $db so you can extend the class for other drivers (i.e Oracle). Otherwise you are just duplicating the functionalities of mysqli.

Edited by broj1

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.