ขั้นตอนแรก
สร้างไฟล์ class_db.php ในที่นี้ตัวผู้เขียนจะสร้าง ไว้ใน folder connect หรือ root/connect/class_db.php นั้นเอง
จากนั้นเขียน Code แบบตัวอย่าง
โค้ด: เลือกทั้งหมด
<?php
class db {
// สร้าง properties ต่างๆ
var $host;
var $user;
var $pass;
var $db_name;
var $charset;
function __construct(){
$this->host = "localhost";
$this->user = "root";
$this->pass = "leaf";
$this->db_name = "member";
$this->charset = "utf8";
}
// สร้าง function สำหรับการเชือมฐานข้อมูล
function connect(){
$conn = mysql_connect($this->host, $this->user, $this->pass) or die (mysql_error());
// ถ้าเชื่อมต่อสำเร็จ
if( $conn ){
mysql_select_db($this->db_name) or die (mysql_error());
mysql_query("SET NAMES" .$this->charset);
}
return $conn;
}
}
ทดสอบว่าติดต่อได้ไหม สร้างไฟล์ testconnect.php หรือ root/testconnect.php
เขียน code สำหรับ การทดสอบ
โค้ด: เลือกทั้งหมด
<?php
include_once 'connect/class_db.php';
$db = new db();
$conn = $db->connect();
if( $conn ){
echo 'connect complete';
}
?>