Wednesday, August 3, 2022

Read & Write File Dengan PHP

 

1. Berapa Contoh Code untuk read File dangan PHP

Buat file text dengan nama baca.txt

AJAX = Asynchronous JavaScript and XML

CSS =  Cascading Style Sheets

HTML = Hyper Text Markup Language

PHP = PHP Hypertext Preprocessor

SQL = Structured Query Language

SVG = Scalable Vector Graphics

XML = EXtensible Markup Language

lalu simpan file tersebut;

1.1.  Read keseluruhan file text tersebut 

<!DOCTYPE html>

 <html>  

 <body>  

 <?php  

 if(readfile("baca.txt"))

 {

    echo readfile("baca.txt");  

 }

 else echo "file tidak ada";

 ?>  

 </body>  

 </html>  


hasil : 


1.2. PHP Periksa End-Of-File – feof()

<?php

$fileread = fopen("baca.txt", "r") or die("Unable to open file!");

// Output one line until end-of-file

while(!feof($fileread)) {

  echo fgets($fileread) . "<br>";

}

fclose($fileread);

?>

Keterangan :

Fungsi feof() berfungsi untuk memeriksa apakah “end-of-file” (EOF) telah tercapai.

Fungsi feof() berguna untuk melakukan perulangan melalui data yang panjangnya tidak diketahui.


1.3.  PHP Membaca Karakter Tunggal – fgetc()

<?php

$fileread = fopen("baca.txt", "r") or die("Unable to open file!");

// Output one character until end-of-file

while(!feof($fileread)) {

  echo fgetc($fileread);

}

fclose($fileread);

?>

Keterangan :

Fungsi fgetc() digunakan untuk membaca satu karakter dari sebuah file setelah penunjuk file berpindah ke karakter berikutnya.


2. Contoh Code untuk write file dengan PHP

menulis beberapa nama ke dalam file “write.txt”:

2.1.  Menulis ke file kosong

<?php

$ilewrite = fopen("write.txt", "w") or die("Unable to open file!");

$txt = "Dony Tan\n";

fwrite($filewrite, $txt);

$txt = "Mike Lie\n";

fwrite($filewrite, $txt);

fclose($filewrite);

?>

Keterangan  :

data yang di tulis ke file “write.txt” sebanyak 2xi. Setiap menulis ke file, maka akan mengirim string $txt yang pertama berisi “John Tan” dan yang kedua berisi “Jane Lie”. Setelah selesai menulis,  menutup file tersebut menggunakan fungsi fclose().

Jika file write.txt dibuka isi nya :

Dony Tan

Mike Lie


2.2. Overwriting File txt

<?php

$ilewrite = fopen("write.txt", "w") or die("Unable to open file!");

$txt = "PHP Language\n";

fwrite($ilewrite, $txt);

$txt = "Java Language\n";

fwrite($ilewrite, $txt);

fclose($ilewrite);

?>

membuka file “write.txt”, baik Dony dan MIke telah berubah menjadi:

PHP Language

Java Language

Membuat Paginasi Pada Laravel


Beriku adalah langkah-langkah membuat Paginasi pada Laravel :

1. Buatlah database pada phpmyadmi. Kemudian buat tabel karyawan, lalu isi bebarapa data minimal diatas 10 data, supaya biasa menjadi contoh.


2. Setelah itu,  buka file .env kemudian setting database :   DB_DATABASEDB_USERNAME dan DB_PASSWORD


3.  Buka terminal , masuk ke direktori projek dan buatlah sebuah controller,  menjalankan php artisan make:controller KaryawanController lalu bukalah file KaryawanController.php tersebut di  folde app/Http/Controllers. Isi file tersebut dengan script seperti di bawah ini.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

//untuk menggunakan query builder

use DB;

class PegawaiController extends Controller

{

    public function index(){

        //mengambil data karyawan dari database

        $data = DB::table('karyawan')->paginate(10);


        //mengirim data karyawan ke view karyawan

        return view('karyawan', ['karyawan' => $data]);

    }

}

Penjelasan:
use DB  digunakan untuk melakukan transaksi data ke database.
paginate(10) = digunakan untuk membuat paginasi, setiap halaman ditampilkan 10 data maksimal, data selanjutnya akan diampilkan pada page setelahnya.

4. Buat file nama karyawan.simple.php di dalam folder resources/views. Kemudian isi file tersebut :


<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <title>Document</title>

    {{-- bootstrap  --}}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"

integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body>

    <div class="container mt-4">

        <div class="card mb-3">

            {{-- membuat tabel  --}}

            <table class="table table-striped">

                <thead>

                    <tr>

                        <td>Nama</td>

                        <td>Jenis Kelamin</td>

                        <td>Alamat</td>

                    </tr>

                </thead>

                <tbody>

                    {{-- melakukan looping data  --}}

                    @foreach ($karyawan as $item)

                    <tr>

                        <td>{{ $item->nama }}</td>

                        <td>{{ $item->jk == '1' ? 'Laki-laki' : 'Perempuan' }}</td>

                        <td>{{ $item->alamat }}</td>

                    </tr>

                    @endforeach

                </tbody>

            </table>

        </div>

        {{-- membuat paginasii  --}}

        Current Page: {{ $karyawan->currentPage() }}<br>

        Jumlah Data: {{ $karyawan->total() }}<br>

        Data perhalaman: {{ $karyawan->perPage() }}<br>

        <br>

        {{ $karyawan->links() }}

    </div>

</body>

</html>


Penjelasan: 
{{ $karyawan->currentPage() }}  digunakan untuk menampilkan halaman ke berapa saat ini

{{ $karyawan->total() }}  digunakan untuk menampilkan total data

{{ $karyawan->perPage() }}  digunakan untuk menampilkan jumlah data perhalaman

{{ $karyawan->links() }}  digunakan untuk menampilkan paginasi dengan penomoran.
 

5. Buka file AppServiceProvider.php di folder app/Providers kemudian ubah script seperti yang di bawah

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Pagination\Paginator;

class AppServiceProvider extends ServiceProvider

{

    /**

     * Register any application services.

     *

     * @return void

     */

    public function register()

    {

        //

    }


    /**

     * Bootstrap any application services.

     *

     * @return void

     */

    public function boot()

    {

        Paginator::useBootstrap();

    }

}


6. Kemudian buka file web.php lalu tambahkan route. script di bawah 

Route::get('/pegawai', 'App\Http\Controllers\KaryawanController@index');


Setelah itu, Jalankan project,  dengan perintah php artisan serve pada terminal / cmd. Lalu buka http://127.0.0.1:8000/karyawan maka hasilnya 


Membuat Paginasi dengan PHP



Paginasi merupakan proses mengambil keselurahan hasil dan menyebarkan ke beberapa halaman dengan 1 halaman yang record baris di sesuaikan dengan keinginan, supaya membuat lebih mudah untuk dilihat atau dibaca datanya.

Berikut adalah cara membuat Paginasi :
1. Buat file Paginator.class.php

Kelas paginator hanya akan memiliki dua metode dan constructor.

Code kelas Paginator

<?php
class Paginator {
 
     private $_conn;
        private $_limit;
        private $_page;
        private $_query;
        private $_total;
}

Code Kelas construct :

<?php

public function __construct( $conn, $query ) {
     
    $this->_conn = $conn;
    $this->_query = $query;
 
    $rs= $this->_conn->query( $this->_query );
    $this->_total = $rs->num_rows;
     
}

Code Kelas mengambil data ( pada pengambilan data per hal 10 baris isi ) :

<?php
public function getData( $limit = 10, $page = 1 ) {
     
    $this->_limit   = $limit;
    $this->_page    = $page;
 
    if ( $this->_limit == 'all' ) {
        $query      = $this->_query;
    } else {
        $query      = $this->_query . " LIMIT " . ( ( $this->_page - 1 ) * $this->_limit ) . ", $this->_limit";
    }
    $rs             = $this->_conn->query( $query );
 
    while ( $row = $rs->fetch_assoc() ) {
        $results[]  = $row;
    }
 
    $result         = new stdClass();
    $result->page   = $this->_page;
    $result->limit  = $this->_limit;
    $result->total  = $this->_total;
    $result->data   = $results;
 
    return $result;
}

Code kelas membuat link paginasi :

<?php
public function createLinks( $links, $list_class ) {
    if ( $this->_limit == 'all' ) {
        return '';
    }
 
    $last       = ceil( $this->_total / $this->_limit );
 
    $start      = ( ( $this->_page - $links ) > 0 ) ? $this->_page - $links : 1;
    $end        = ( ( $this->_page + $links ) < $last ) ? $this->_page + $links : $last;
 
    $html       = '<ul class="' . $list_class . '">';
 
    $class      = ( $this->_page == 1 ) ? "disabled" : "";
    $html       .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . ( $this->_page - 1 ) . '">&laquo;</a></li>';
 
    if ( $start > 1 ) {
        $html   .= '<li><a href="?limit=' . $this->_limit . '&page=1">1</a></li>';
        $html   .= '<li class="disabled"><span>...</span></li>';
    }
 
    for ( $i = $start ; $i <= $end; $i++ ) {
        $class  = ( $this->_page == $i ) ? "active" : "";
        $html   .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . $i . '">' . $i . '</a></li>';
    }
 
    if ( $end < $last ) {
        $html   .= '<li class="disabled"><span>...</span></li>';
        $html   .= '<li><a href="?limit=' . $this->_limit . '&page=' . $last . '">' . $last . '</a></li>';
    }
 
    $class      = ( $this->_page == $last ) ? "disabled" : "";
    $html       .= '<li class="' . $class . '"><a href="?limit=' . $this->_limit . '&page=' . ( $this->_page + 1 ) . '">&raquo;</a></li>';
 
    $html       .= '</ul>';
 
    return $html;
}

2. Buat file index.php ( untuk menggunakan class Paginator  dan menampilkan data )  juga menggunakan bootstrap dasar styling halaman:

<!DOCTYPE html>
    <head>
        <title>PHP Pagination</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
    </head>

<?php
    require_once 'Paginator.class.php';
 
    $conn       = new mysqli( '127.0.0.1', 'root', 'root', 'world' );
 
    $limit      = ( isset( $_GET['limit'] ) ) ? $_GET['limit'] : 25;
    $page       = ( isset( $_GET['page'] ) ) ? $_GET['page'] : 1;
    $links      = ( isset( $_GET['links'] ) ) ? $_GET['links'] : 7;
    $query      = "SELECT City.Name, City.CountryCode, Country.Code, Country.Name AS Country, Country.Continent, Country.Region FROM City, Country WHERE City.CountryCode = Country.Code";
 
    $Paginator  = new Paginator( $conn, $query );
 
    $results    = $Paginator->getData( $page, $limit );
?>

    <body>
        <div class="container">
                <div class="col-md-10 col-md-offset-1">
                <h1>PHP Pagination</h1>
                <table class="table table-striped table-condensed table-bordered table-rounded">
                        <thead>
                                <?php for( $i = 0; $i < count( $results->data ); $i++ ) : ?>
        <tr>
                <td><?php echo $results->data[$i]['Name']; ?></td>
                <td><?php echo $results->data[$i]['Country']; ?></td>
                <td><?php echo $results->data[$i]['Continent']; ?></td>
                <td><?php echo $results->data[$i]['Region']; ?></td>
        </tr>
<?php endfor; ?>
                        </tr>
                        </thead>
                        <tbody></tbody>
                </table>
<?php echo $Paginator->createLinks( $links, 'pagination pagination-sm' ); ?>
                </div>
        </div>
        </body>
</html>

Hasil :


Tuesday, August 2, 2022

Membuat CRUD Database Dengan Laravel - V [ Print ]


Disetiap program tentu membutuhkan laporan, apalagi juga program yang brkaitan dengan data. Pada Laravel membuat atau generate sebuah laporan sudah mudah dan biasa dipakai dalam generate sebuah laporan adalah bentuk Laporan PDF.

Berikut adalah langkah-langkah membuat laporan di Laravel : Nah, pada tutorial ini kita akan sama-sama belajar. bagaimana membuat laporan dalam bentuk PDF menggunakan laravel 7. kita akan memanfaatkan 

1. Download  package laravel-dompdf


kemudian install package tersebut dengan  perintah seperti berikut:

composer require barryvdh/laravel-dompdf

Setelah selesai install, maka buka routes/web.php lalu buat routing seperti berikut:

Route::get('/', function () {

    return view('index');

});

Pada sintak diatas akan membuat halaman awal web mengarah ke file index. Selanjutnya buat file index.simple.php pada resources\views . isikan kode html. dan tambahkan CDN Bootstrap pada bagian head seperti dibawah ini 

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" >

<script src="https://stackpath.boot

Kemudian bagian body tambahkan tabel yang akan digenerate menjadi PDF

<div class="container">

        <div class="row">

                <table class="table">

                        <thead class="thead-dark">

                          <tr>

                            <th scope="col">No</th>

                            <th scope="col">First Name</th>

                            <th scope="col">Last Name</th>

                            <th scope="col">Address</th>

                          </tr>

                        </thead>

                        <tbody>

                          <tr>

                            <th scope="row">1</th>

                            <td>Mark</td>

                            <td>Otto</td>

                            <td>Surabaya</td>

                          </tr>

                          <tr>

                            <th scope="row">2</th>

                            <td>Jacob</td>

                            <td>Thornton</td>

                            <td>Sidoarjo</td>

                          </tr>

                          <tr>

                            <th scope="row">3</th>

                            <td>Larry</td>

                            <td>the Bird</td>

                            <td>Mojokerto</td>

                          </tr>

                        </tbody>

                      </table>

        </div>

        <div class="row">

            <a href="{{ route('print')}}" class="btn btn-sm btn-danger"> Print</a>

        </div>

    </div>

Bagian bawah ditambahkan tombol untuk melakukan cetak atau print.  tampilan yang dibuat menjadi seperti gambar dibawah :


Lalu membuat sebuah controller, dengan perintah berikut:

Php artisan make:controller PdfController

Kemudian pada PdfController, buat fungsi untuk melakukan generate ke PDF seperti berikut:

use PDF; 

public function print()

{

    $pdf = PDF::loadview('index')->setPaper('A4','potrait');

    return $pdf->stream();

}

Setelah itu buat sebuah routing agar tombol print di klik maka akan melakukan export ke bentuk PDF

Route::get('/pdf', 'PdfController@pdf')->name('print');

Silahkan di jalankan dan lihat hasil dari laporan yang sudah digenerate ke Pdf.

Memunculkan Simbol & Emoji Pada OS Mac

  Memunculkan Simbol & Emoji  1. Buka aplikasi Pages / Notes pada Macbook. 2. Klik pada Menubar Edit --> Pilih Emoji and Symbols a...