Dharmana
Dharmana

Reputation: 99

Codeigniter: How to make Autonumber

I'm developing application that need unique code such as: TS001, TS0002, TS003

I have PHP source code for autonumber like this:

function autoNumber($tabel, $kolom, $lebar=0, $awalan) {
    $q = mysql_query("SELECT $kolom FROM  $tabel ORDER BY $kolom DESC LIMIT 1");
    $jum = mysql_num_rows($q);


    if($jum == 0) {
        $nomor = 1;
    } else {
        $data = mysql_fetch_array($q);
        $nomor = intval(substr($data[0],strlen($awalan))) + 1;
    }

    if($lebar > 0) {

        $angka = $awalan.str_pad($nomor,$lebar,"0",STR_PAD_LEFT);

    } else {

        $angka = $awalan.$nomor;
    }
    return $angka;

}

But i have a problem when i try it on Codeigniter.

My latest code on Codeigniter :

function autoNumber($tabel, $kolom, $lebar=0, $awalan) {
    $q = $this->db->query("SELECT $kolom FROM  $tabel ORDER BY $kolom DESC LIMIT 1");


    $this->db->order_by($kolom, "desc");
    $this->db->limit(1);
    $this->db->from('my_table');
    $data['jum'] = $this->db->count_all_results();


    foreach ($jum as $r) {
        # code...


    if($jum == 0) {
        $nomor = 1;
    } else {
        $data = mysql_fetch_array($q);
        $nomor = intval(substr($data[0],strlen($awalan))) + 1;
    }

    if($lebar > 0) {

        $angka = $awalan.str_pad($nomor,$lebar,"0",STR_PAD_LEFT);

    } else {

        $angka = $awalan.$nomor;
    }



    }

     return $angka;


}

Upvotes: 1

Views: 2660

Answers (2)

Imran Qamer
Imran Qamer

Reputation: 2263

first of all your query has ORDER BY $kolom DESC LIMIT 1 clauses and you are also using

 $this->db->order_by($kolom, "desc");
 $this->db->limit(1);

which is not good so first try to set your query like

$this->db->select("$kolom);
$this->db->order_by($kolom, "desc");
$this->db->limit(1);
$this->db->from($tabel);
$query = $this->db->get();
$rslt = $query->result_array();

then

$total_rec = $query->num_rows();
if ($total_rec == 0) {
    $nomor = 1;
} else {
    $nomor = intval(substr($rslt[0][$kolom],strlen($awalan))) + 1;
}

Upvotes: 0

GluePear
GluePear

Reputation: 7735

Your calls to db are a bit confused. Try this:

function autoNumber($tabel, $kolom, $lebar=0, $awalan) {
    $this->db->order_by($kolom, "desc");
    $this->db->limit(1);
    $query = $this->db->get($tabel);
    $rows = $query->row();
    $jum = $query->num_rows();
    if ($jum == 0) {
      $nomor = 1;
    } else {
      $nomor = intval(substr($rows[0],strlen($awalan))) + 1;
    }
}

Upvotes: 1

Related Questions