Search code examples
mysqlcodeigniterauto-increment

How to generate auto increment id manually using codeigniter


I am new in Codeigniter. Without using auto increment in database i want to generate auto increment manually like A00001, A00002, A00003 .......

How can i generate this type of ID using codeigniter and mysql database?


Solution

  • Actually, automatic auto increment is better for a primary key. But if you want to generate it, you can do it like this

    function GenerateId() {
        $query = $this->db->select('ID')
                          ->from('table_name')
                          ->get();
        $row = $query->last_row();
        if($row){
            $idPostfix = (int)substr($row->ID,1)+1;
            $nextId = 'A'.STR_PAD((string)$idPostfix,5,"0",STR_PAD_LEFT);
        }
        else{$nextId = 'A00001';} // For the first time
        return $nextId;
    }