PHP OOP CONNECT MYSQL

PHP OOP CONNECT MYSQL



PHP OOP CONNECT MYSQL ตัวนี้มีการ RETURN ค่าเป็น ARRAY ครับ ลองนำไปใช้ดู

 Class connectDB { private $_host = "localhost"; private $_user = "root"; private $_pass = "db_pass"; private $_db = "oop_test_db"; // Will need a new class Error to handle all errors private function openDB() { $charset = "set names utf8"; $link = mysql_pconnect($this->_host, $this->_user, $this->_pass); if (!$link) { die('Could not connect to the server: ' . mysql_error()); } $db_selected = mysql_select_db($this->_db, $link); if (!$db_selected) { die ('Could not connect to the database"' . $this->_db ." get error: " . mysql_error()); } mysql_query($charset) or die('Invalid query: ' . mysql_error()); } private function closeDB() { mysql_close($link); } public function return_sql($sql) { self::openDB(); $result = mysql_query($sql); if ($result){ $arrData = array(); while ($rows = mysql_fetch_array($result)) {$arrData[] = $rows;} }else{ $message = 'ชุดคำสั่งของ : ' . mysql_error() . " ไม่ถูกต้อง
"; // $message .= 'Whole query: ' . $query; $message = mysql_error(); die($message); } //return the result to a function that will build the right table. return $arrData; self::closeDB(); } public function exe($sql) { self::openDB(); $result = mysql_query($sql); if (!$result) { $message = 'ชุดคำสั่งของ : ' . mysql_error() . " ไม่ถูกต้อง
"; die($message); } } } $conn = new connectDB; $sSql = "DELETE FROM tbl_oop_test"; $arrData = $conn->exe($sSql); $conn = new connectDB; $sSql = "INSERT INTO tbl_oop_test (test_name,test_surname) VALUES('ทดสอบ','นามสกุล')"; $arrData = $conn->exe($sSql); $conn = new connectDB; $sSql = "UPDATE tbl_oop_test SET test_name = 'ชื่อเสียงเรียงนาม'"; $arrData = $conn->exe($sSql); $conn = new connectDB; $sSql = "SELECT count(*) FROM tbl_oop_test"; $arrData = $conn->return_sql($sSql); print "Recordcount = " . $arrData[0][0] . "
"; $conn = new connectDB; $sSql = "SELECT * FROM tbl_oop_test"; $arrData = $conn->return_sql($sSql); print "Name = " . $arrData[0][1] . ""; print "Surname = " . $arrData[0][2] . "";


ฝากติดตามผลงานด้านล่างด้วยครับ
--------------------------
► Website : http://www.siamfocus.com/
► LINE@ : http://line.me/ti/p/@siamfocus.com
► Facebook : https://www.facebook.com/fanpage.siamfocus
► Twitter : https://twitter.com/siamfocus
► Google+ : https://plus.google.com/+TAAMSiAMFOCUS
► Instagram : https://www.instagram.com/iamtaam
--------------------------









บทความ แนะนำ




หมวดหมู่บทความ