Hello,

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:

<?php

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

    public function query($sql){
        $this->result = $this->mysqli->query($sql);
        if($this->result == true){
            return true;
        }else{
            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;
        }

        $this->result->close();
        return $data;
    }

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

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.

Recommended Answers

All 2 Replies

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.

Worked like a charm. Thanks alot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.