Skip to content

Instantly share code, notes, and snippets.

@Aziz-Rahman
Created April 17, 2015 09:20
Show Gist options
  • Save Aziz-Rahman/f339b2e586bfc6a6e07c to your computer and use it in GitHub Desktop.
Save Aziz-Rahman/f339b2e586bfc6a6e07c to your computer and use it in GitHub Desktop.
Kode unix automatic in form input
<?php
$conn = mysqli_connect( "localhost", "root", "", "no_urut" ) or die ( "Error !".mysqli_error( $conn ) );
// Date
date_default_timezone_set( 'Asia/Jakarta' );
$date = date( 'Y' );
$get3number = substr( $date,-3 ); //get 3 number of years from right
// Random of the character
function random_char( $panjang ) {
$karakter= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$string = '';
for ( $i = 0; $i < $panjang; $i++ ) {
$pos = rand( 0, strlen( $karakter ) - 1);
$string .= $karakter{$pos};
}
return $string;
}
// Get data from database
$get_data = mysqli_query( $conn, "SELECT *FROM kode" );
// Check
$check = mysqli_num_rows( $get_data );
// var_dump( $check ); -> to check variable
if ( empty( $check ) ){
$kd = 1;
} else {
$kd = $check + 1;
}
?>
<form action="save-kode.php" method="post">
Kode: <input type="text" name="automatic_number" value="<?php echo random_char(3) . $get3number . '-' . $kd; ?>" readonly>
<input type="submit" name="save_kode" value="Save !">
</form>
<!-- File save-kode.php -->
<?php
$conn = mysqli_connect( "localhost", "root", "", "no_urut" ) or die ( "Error !".mysqli_error( $conn ) );
$kode = mysqli_real_escape_string( $conn, $_POST['automatic_number'] );
$sql = mysqli_query( $conn, "INSERT INTO kode( kode_unik ) VALUES( '$kode' )" );
if ( $sql ) {
echo "<script>alert( 'Berhasil disimpan !' ); window.location='./';</script>";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error( $conn );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment