
PHP : PHP Connect to MySQL
สวัสดีครับ ชาว Dev วันนี้ผมเอา Class Connection มาฝากครับ ซึ่งตัวนี้ผมทำเก็บไว้ใช้ประจำครับ
สามารถนำไปทำ include file ไปใช้ได้เลยครับ และมีการเรียกใช้ค่อนข้างสั้น นำไปใช้ได้กับทุกๆ งานครับ
<?
class connectDB
{
private $_host = "##YOUR_SERVER_NAME##";
private $_user = "##YOUR_DATABASE_USER##";
private $_pass = "##YOUR_DATABASE_PASSWORD##";
private $_db = "##YOUR_DATABASE_NAME##";
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);
$num_rows = mysql_num_rows($result);
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 record_count($sql)
{
self::openDB();
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
return $num_rows;
self::closeDB();
}
public function exe($sql)
{
self::openDB();
$result = mysql_query($sql);
if (!$result) {
$message = 'ชุดคำสั่งของ : ' . mysql_error() . " ไม่ถูกต้อง
";
die($message);
}
}
}
?>
มาดูคำสั่งในการใช้งานครับ คำสั่งเกี่ยวกับการ Excecute นะครับ ได้แก่
INSERT ,UPDATE ,DELETE
$sSql = "DELETE FROM TABLE_NAME";
$conn = new connectDB;
$conn->exe($sSql);
$sSql = "INSERT INTO TABLE_NAME (FILED1,FILED2) VALUES('VALUE1','VALUE2')";
$conn = new connectDB;
$conn->exe($sSql);
$sSql = "UPDATE TABLE_NAME SET FILED1 = 'VALUE1'";
$conn = new connectDB;
$conn->exe($sSql);
?>
ส่วนคำสั่งที่ใช้ในการ SELECT ข้อมูล และนับจำนวนของ Reccord จะใช้ คำสั่งแบบนี้ครับ
$sSql = "SELECT FILED1,FILED2 FROM TABLE_NAME ";
$conn = new connectDB;
$arrData = $conn->return_sql($sSql);
$recCount = $conn->record_count($sSql);
if($recCount>0){
for($iLoop=0;$iLoop<$recCount;$iLoop++){
echo $arrData[$iLoop][0] . " " . $arrData[$iLoop][1];
echo "
";
}
}
?>
ลองเอาไปประยุกใช้ดูนะครับ
มาเป็นเพื่อนกันครับ บนช่องทาง Social ด้านล่างนี้ครับ
--------------------------► LINE@ : @siamfocus.com
► Facebook : fanpage.siamfocus
► Twitter (X) : siamfocus
► Linkedin : taam-siamfocus
► Instagram : iamtaam
► Youtube : SiAMFOCUS
► Tiktok : @taamsiamfocus
--------------------------