user3740978
user3740978

Reputation: 7

adding serial number on string php

I have these codes:

    //ambil nomor surat maksimum pada tabel surat_keterangan
$query = "SELECT MAX(nomor_surat) as noMax FROM surat_keterangan";
$result = mysqli_query($link,$query);
$row  = mysqli_fetch_array($result);
$nomor = $row['noMax'];
    //ambil karakter nomor urut surat paling kiri sebanyak 1 karakter (0, 1)
$noUrut = (int) substr($nomor, 0, 1);
$noUrut++;

//mengambil bulan dan tahun dari tanggal surat
$bulan = substr($tgl_surat,3,2);
$tahun = substr($tgl_surat,6,4);

//membuat nomor surat
$nomor_surat = $noUrut."/SK/".$bulan."/DPK3/".$tahun;

the output will be

1/SK/06/DPK3/2014.

the first string (1) will add every time I insert data. I have tried until 10/SK/06/DPK3/2014, but when I continued to input, the output still

10/SK/06/DPK3/2014, not 11/SK/06/DPK3/2014.

is there another way? thank you for every responses and answers.

Upvotes: 0

Views: 293

Answers (2)

pavel
pavel

Reputation: 27072

Problem is on line with $noUrut = (int) substr($nomor, 0, 1); where you take alwazy the first character (when string begins with 10, you take 1only and 1++ makes 2.

So, you need to find first slash (/) position and than use substr.

$noUrut = (int)substr($nomor, 0, strpos($nomor, '/'));
$noUrut++;

OR just oneline

$noUrut = (int)substr($nomor, 0, strpos($nomor, '/')) + 1;

Upvotes: 0

olele
olele

Reputation: 69

Is your field "nomor_surat" using varchar variable? if so then you need to convert it to int

how to query get max id from varchar type and the values in numeric?

Upvotes: 1

Related Questions