我正在开发需要唯一代码的应用程序,例如: TS001,TS0002,TS003
我有自动编码的PHP源代码,如下所示:
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;
}
但是当我在Codeigniter上尝试时,我遇到了问题。
我在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;
}
答案 0 :(得分:1)
您对db
的来电有点困惑。试试这个:
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;
}
}
答案 1 :(得分:0)
首先你的查询有ORDER BY $ kolom DESC LIMIT 1条款,你也在使用
$this->db->order_by($kolom, "desc");
$this->db->limit(1);
这不好,所以首先尝试设置您的查询
$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();
然后
$total_rec = $query->num_rows();
if ($total_rec == 0) {
$nomor = 1;
} else {
$nomor = intval(substr($rslt[0][$kolom],strlen($awalan))) + 1;
}