- Siapkan file koneksi.php (lihat tutorial sebelumnya)
-
Persiapakan db nya
db name nya : test
table name : mhs (id,nama,alamat,nim)
- buat file active_record.php
kita akan membuat Class helper untuk menampilkan data dengan PDO. sebenarnya bisa Query langsung ke mysql. Tapi sebaiknya kita buat Class helper agar kode nya bisa dipakai dimana saja dikemudian hari. Ketikan kode berikut
/*----------------------------------------------------- Db_connect adalah class koneksi di tutorial sebelumnya ------------------------------------------------------*/ include "koneksi.php" class Active_record extends Db_connect{ public function __construct(){} public function fetchObject($sql){ $clone = array(); try{ $data = $this->getConnect()->prepare($sql); $data->setFetchMode(PDO::FETCH_INTO,new Active_record()); $data->execute(); while($result = $data->fetch()){ $clone[] = clone $result; } $this->closeConnect(); }catch(PDOException $e){ echo $e->getMessage(); } return $clone; } }
Buat file index.php . kita akan mengolah output nya disini saja.
class Mhs{ public $nama; Public $nim; Public $alamat; Public $id; public function __construct(){ $this->nama = $this->nama; $this->alamat = $this->alamat; $this->nim = $this->nim; $this->id = $this->id; } public function getMhs(){ $objAr = new Active_record(); $sql = "select * from mhs"; $result = $objAr->fetchObject($sql); return $result; } } $objMsh = new mhs(); $table = "
Id | Nim | Nama | Alamat |
---|---|---|---|
".$row->id." | ".$row->nim." | ".$row->nama." | ".$row->alamat." |
Id | Nim | Nama | Alamat |
---|---|---|---|
1 | 343243242343 | bgfnhgn | hgnghn |
2 | 64543545 | jhhk | sfdsg |
Diatas adalah outputnya. Cheeerssss.