擷取自:php - MySQL 教學
物件導向的方式
通常我會寫兩個檔案,一個是DB_config.php,另外一個是DB.class.php
DB_config.php就是很簡單的設定database的位址、username、password以及使用的資料表
<?php
global $_DB;
$_DB['host'] = "localhost";
$_DB['username'] = "username";
$_DB['password'] = "password";
$_DB['dbname'] = "db_name";
?>
另外再寫一個DB_Class.php檔
<?php
class DB
{
var $_dbConn = 0;
var $_queryResource = 0;
function DB(){
//do nothing
}
function connect_db($host, $user, $pwd, $dbname){
$dbConn = mysql_connect($host, $user, $pwd);
if (! $dbConn)
die ("MySQL Connect Error");
mysql_query("SET NAMES utf8");
if (! mysql_select_db($dbname, $dbConn))
die ("MySQL Select DB Error");
$this->_dbConn = $dbConn;
return true;
}
function query($sql){
if (! $queryResource = mysql_query($sql, $this->_dbConn))
die ("MySQL Query Error");
$this->_queryResource = $queryResource;
return $queryResource;
}
/** Get array return by MySQL */
function fetch_array(){
return mysql_fetch_array($this->_queryResource, MYSQL_ASSOC);
}
function fetch_row(){
return mysql_fetch_row($this->_queryResource);
}
function get_num_rows(){
return mysql_num_rows($this->_queryResource);
}
/** Get the cuurent id */
function get_insert_id(){
return mysql_insert_id($this->_dbConn);
}
}
?>
最後在要使用mysql的php file裡面
<?php
require_once("DB_config.php");
require_once("DB.class.php");
$db = new DB();
$db->connect_db($_DB['host'], $_DB['username'], $_DB['password'], $_DB['dbname']);
$db->query("SELECT ....");
while($result = $db->fetch_array())
{
// do something you want...
$result["欄位名稱"];
}
?>
全站熱搜
留言列表