untuk lebih lengkapnya anda dapat membaca artikel berikut:
http://www.phpeveryday.com/articles/PHP-Data-Object/PDO-Tutorial-P842.html
Langsung saja kepada implementasinya, pada kasus kali ini kita menggunakan PDO untuk MySQL, tapi pastikan terlebih dahulu di PHP info bahwa extension PDO telah terinstal.
database.php
<?php class DB { /*** mysql hostname ***/ private $hostname = 'localhost'; /*** mysql username ***/ private $username = 'username'; /*** mysql password ***/ private $password = 'password'; /*** mysql password ***/ private $dbName = 'db'; // /*** database resource ***/ public $dbh = NULL; public function __construct() { try { $this->dbh = new PDO("mysql:host=$this->hostname;dbname=$this->dbName", $this->username, $this->password); } catch(PDOException $e) { echo __LINE__.$e->getMessage(); } } public function __destruct() { $this->dbh = NULL; } public function runQuery($sql) { try { //echo $sql; $count = $this->dbh->exec($sql) or print_r($this->dbh->errorInfo()); } catch(PDOException $e) { echo __LINE__.$e->getMessage(); } } public function getQuery($sql) { $stmt = $this->dbh->query($sql); $stmt->setFetchMode(PDO::FETCH_ASSOC); return $stmt; } } ?>Dan untuk implementasinya
<?php include('Database.php'); // Include class $dataBase = new DB; // Membuat objek database $sqlInsert = "INSERT INTO testTable (`test1`, `test2`) VALUES('This', 'is a test')"; // Contoh sederhana statement Insert $dataBase->runQuery($sqlInsert); // menjalankan query SQL $sqlSelect = "SELECT test1, test2 FROM testTable WHERE test1 = 'This'"; // SQL SELECT sederhana $data = $dataBase->getQuery($sqlSelect); //Menjalankan query sql dan mengembalikan nilai berupa array foreach($data as $d) { echo $d["test1"]." ".$d["test2"]."!"; // Menampilkan output } ?>
Samapai disini tutorial PDO kita kali ini, selamat mencoba...
0 komentar:
Posting Komentar