1

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.

2
Contributors
2
Replies
9
Views
4 Years
Discussion Span
Last Post by Martin C++
1
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.