Search code examples
phpcodeigniter-4

ErrorException Undefined property: mysqli::$kd_max


I was trying to make unique code based on date,

Here's my Model for creating the unique code :

public function get_kode()
{
    $q = $this->db->query("SELECT MAX(RIGHT(kode_list,4)) AS kd_max FROM list_produksi_toko");
    $kd = "";
    if($q->getResult() > 0){
        foreach($q as $k){
            $tmp = ((int)$k->kd_max)+1;
            // $kd = sprintf("%04s", $tmp);
            $kd = sprintf("%'.04d", $tmp);
        }
    }else{
        $kd = "0001";
    }
    date_default_timezone_set('Asia/Jakarta');
    return date('ym').$kd;
}

it wont work and show error just like in the title, but if i change this :

if($q->getResult() > 0){

to this :

if($q->getResult() < 0){

It work, but it keep showing "20090001" the same code even after i input it to database.

What can i do to make it generate unique code, like if "20090001" is already exist it will make "20090002"


Solution

  • Try This,

    public function get_kode()
    {
        $q = $this->db->query("SELECT MAX(RIGHT(kode_list,4)) AS kd_max FROM list_produksi_toko");
        $kd = "";
        $result = $q->getResult();
        // try to use $q->getRow(); to get single row and reduce the code of **for loop**
        if(isset($result)){
            foreach($result as $k){//change
                $tmp = ((int)$k->kd_max)+1;
                // $kd = sprintf("%04s", $tmp);
                $kd = sprintf("%'.04d", $tmp);
            }
        }else{
            $kd = "0001";
        }
        date_default_timezone_set('Asia/Jakarta');
        return date('ym').$kd;
    }