Kunci kode otomatis

Pada kesempatan kali ini, caraguna akan membahas sedikit tentang bagaimana cara membuat script atau kode secara otomatis di PHP mysql yang nantinya bisa digunakan sebagai primary key pada tabel dalam database. Tentunya kode yang dihasilkan nantinya bersifat unik.

Kenapa harus membuat kode otomatis?

Mungkin salah satu dari kalian ada yang masih bingung kenapa harus membuat kode otomatis? bukannya di database mysql juga sudah ada fitur auto increment. Memang benar, dalam mysql ada fitur yang namanya auto increment dimana nantinya field tabel akan terisi secara otomatis, namun kode yang dihasilkan sangat sederhana, hanya berupa nomor urut saja dari 1 sampai n (banyak data).

Nah, jika kita ingin membuat kode yang kita inginkan, maka kita perlu membuat kode secara manual melalui script yang akan saya jelaskan nantinya. Tentunya dengan adanya custom kode yang akan kita generate, membuat tingkat keamanan database kita semakin baik.

Oke, langsung saja ya kita mulai tutorial untuk membuat kode otomatis di php mysql ini. Pertama yang perlu kalian siapkan adalah

  • Xampp,
  • Browser,
  • Code editor.

Buat database di phpmyadmin, disinisaya mencontohkan dengan memberi nama database saya caraguna-database. Setelah itu buat tabel barang dengan field kode barang dan nama barang. Atau jika tidak ingin ribet, kalian bisa menjalankan sintaks dibawah ini :

CREATE TABLE IF NOT EXISTS `tbl_barang` (
`kode_barang` varchar(20) NOT NULL,
`nama_barang` varchar(40) NOT NULL,
PRIMARY KEY (`kode_barang`)
)

1. Buat koneksi ke server

Karena kita membuat kode pada bahasa pemrograman php, maka kita perlu menjalankannya kedalam sebuah server dengan memakai bantuan aplikasi xampp. Buat file dengan nama koneksi.php seperti dibawah.

$host       =   "localhost";
$user       =   "root";
$password   =   "";
$database   =   "caraguna_database";
$connect = mysqli_connect($host, $user, $password, $database);

2. Generate Kode

Setelah itu, buat file baru lagi dengan nama getid.php. Jangan lupa untuk menempatkan file ini dalam satu folder dengan file koneksi.php

include "koneksi.php";

$query = "SELECT max(kode_barang) as maxKode FROM tbl_barang";
$hasil = mysqli_query($connect,$query);
$data = mysqli_fetch_array($hasil);
$kodeBarang = $data['maxKode'];

$noUrut = (int) substr($kodeBarang, 3, 3);
$noUrut++;

$char = "BRG";
$kodeBarang = $char . sprintf("%03s", $noUrut);
echo $kodeBarang;

// Output :
// BRG001

3. Bedah kode

Oke teman-teman, jika kalian belum paham kode diatas, jangan khawatir karena mimin juga akan membahas kode yang barusan kita buat dari baris ke baris.

Baca juga :  Mengenal Apa Itu JSON (Javascript Object Notation)

Untuk bagian poin pertama yaitu membuat tabel dalam database maupun menghubungkan php dengan database mysql, kita tidak perlu bahas lah ya, karena saya yakin kalian sudah paham. yang akan kita bahas kali ini yaitu poin ke dua, generate kode otomatis.

Pertama, agar file getid.php dapat terhubung juga dengan database maka kita perlu mengimport file koneksi.php yang sudah kita buat tadi dalam satu folder.

include "koneksi.php";

Kedua, jalankan sebuah query untuk menyeleksi tabel dan field mana yang akan dibuatkan sebuah kode baru. Cari nilai maksimalnya lalu simpan didalam tabel sementara dengan nama maxKode.

$query = "SELECT max(kode_barang) as maxKode FROM tbl_barang";

Jangan lupa eksekusi query tersebut dan tangkap (fetch) nilai/hasilnya dalam bentuk array lalu simpan kedalam variabel $data.

$hasil = mysqli_query($connect,$query);
$data = mysqli_fetch_array($hasil);

Ingat, tadi kan kita sudah menyeleksi tabel dan field kedalam tabel sementara yaitu maxKode, lalu kita panggil saja nilainya dan masukkan kedalam variabel $kodeBarang.

$kodeBarang = $data['maxKode'];

Kemudian kita dapatkan nilai kode baru dengan cara menjumlahkan 1 angka pada kode barang agar tidak terjadi redundansi data serta kode bertambah secara terus menerus apabila kita panggil file getid.php. fungsi substr berfungsi untuk memecah huruf dan angka pada kode barang sebelumnya (jika kode sebelumnya berupa gabungan huruf dan angka), simpan dalam fairabel $noUrut.

$noUrut = (int) substr($kodeBarang, 3, 3);
$noUrut++;

Setelah itu, jika kita ingin menambahkan huruf didepan kode, buat variabel baru dengan nama $char dan isikan sesuai keinginan kalian. gabung dengan kode baru yang kita simpan didalam variabel $noUrut tadi. Simpan hasil gabungan ke dalam variabel $kodeBarang. Tampilkan dengan menggunakan echo, selesai.

$char = "BRG";
$kodeBarang = $char . sprintf("%03s", $noUrut);
echo $kodeBarang;

Itulah tadi tutorial membuat sebuah kode otomatis pada php mysqli dengan mudah. Semoga dapat bermanfaat, jika ada yang ingin ditanyakan atau ada yang ingin disampaikan, silahkan komen pada kolom komentar dibawah.

Baca juga :  Pilih Mana Codeigniter Atau Laravel? Gausah Bingung!

Apakah Artikel Diatas Bermanfaat?

Kasih rating dong kak 😀

Average rating 5 / 5. Jumlah vote: 2

Masih belum ada yang rate nih!

24 thoughts on “Membuat Kode Otomatis di PHP Mysqli dengan Mudah!”

  1. Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something.
    I think that you could do with some pics to drive the message
    home a little bit, but other than that, this is great blog.
    A fantastic read. I’ll definitely be back.

  2. Good day! This is kind of off topic but I need some guidance from an established blog.
    Is it tough to set up your own blog? I’m not very techincal but I can figure things out pretty quick.

    I’m thinking about making my own but I’m not sure where to
    begin. Do you have any tips or suggestions? Thanks

    Also visit my web blog … real psychics readings!

  3. I’m curious to find out what blog system you happen to be utilizing?
    I’m having some minor security issues with my latest blog and I would like to
    find something more safe. Do you have any recommendations?

  4. Wow, awesome blog structure! How lengthy have you been running
    a blog for? you made running a blog look easy. The entire glance of your web site is great,
    let alone the content!

  5. Thanks for the marvelous posting! I quite enjoyed reading it, you may
    be a great author.I will be sure to bookmark your blog and will come back from now
    on. I want to encourage yourself to continue
    your great writing, have a nice day!

  6. Good day! This is my first visit to your blog! We are a
    group of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us beneficial information to work on. You have done a marvellous job!

  7. Oh my goodness! Awesome article dude! Thanks, However I am going through difficulties with
    your RSS. I don’t understand why I cannot subscribe to it.
    Is there anybody else having the same RSS issues? Anyone who knows the solution can you kindly respond?
    Thanx!!

  8. After looking over a few of the blog articles on your web site,
    I seriously appreciate your technique of writing a blog.

    I book marked it to my bookmark site list and will
    be checking back in the near future. Take a look at my web site as well and let me know how you feel.

  9. Yesterday, while I was at work, my sister stole my iphone and
    tested to see if it can survive a 25 foot drop,
    just so she can be a youtube sensation. My iPad is now broken and she
    has 83 views. I know this is entirely off topic but I had to share it with
    someone!

  10. You are so cool! I don’t think I have read a single thing
    like that before. So wonderful to discover somebody with
    a few original thoughts on this subject. Really.. thanks for starting this up.
    This web site is one thing that is needed on the web, someone with a little originality!

  11. A person essentially help to make critically articles I would state.
    This is the very first time I frequented your web page and to this point?
    I amazed with the research you made to make this particular
    submit incredible. Fantastic task!

  12. Link exchange is nothing else except it is only placing the
    other person’s webpage link on your page at proper place and other person will also do
    similar in support of you.

  13. Please let me know if you’re looking for a article writer for your site.
    You have some really great articles and I feel I would be a good asset.
    If you ever want to take some of the load off, I’d absolutely
    love to write some content for your blog in exchange for a link back
    to mine. Please shoot me an email if interested. Regards!

  14. I all the time used to study post in news papers but now as I am a user of internet
    thus from now I am using net for articles or reviews,
    thanks to web.

  15. hello there and thank you for your info – I have
    definitely picked up anything new from right here. I did however expertise several technical issues using this website, since I experienced to reload the web site a lot of times previous to I could get
    it to load properly. I had been wondering if your hosting
    is OK? Not that I am complaining, but sluggish loading instances times will often affect your placement in google and can damage your high quality score if advertising
    and marketing with Adwords. Well I am adding this RSS to my email
    and can look out for a lot more of your respective interesting content.
    Make sure you update this again soon.

  16. Have you ever considered about including a little bit
    more than just your articles? I mean, what you say is valuable and all.

    But just imagine if you added some great pictures or videos to give your posts more, “pop”!
    Your content is excellent but with pics and clips, this
    site could undeniably be one of the best in its niche.
    Awesome blog!

  17. Hello would you mind sharing which blog platform you’re using?
    I’m planning to start my own blog soon but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your design and style seems different then most
    blogs and I’m looking for something unique.
    P.S My apologies for being off-topic but I had to ask!

Leave a Reply

Your email address will not be published. Required fields are marked *

Close
Caraguna

Gudang Teknologi Informasi

Thursday, Nov 26, 2020