class sqlHelper{ \x0d\x0a public $conn; \x0d\x0a public $dbname="數(shù)據(jù)庫名稱"; \x0d\x0a public $username="數(shù)據(jù)庫用戶名"; \x0d\x0a public $password="數(shù)據(jù)庫密碼"; \x0d\x0a public $host="localhost"; \x0d\x0a //連接數(shù)據(jù)庫 \x0d\x0a public function __construct(){ \x0d\x0a $this-conn=mysql_connect($this-host,$this-username,$this-password); \x0d\x0a if(!$this-conn){ \x0d\x0a die("連接失敗".mysql_error()); \x0d\x0a } \x0d\x0a mysql_select_db($this-dbname,$this-conn); \x0d\x0a } \x0d\x0a //執(zhí)行查詢語句 \x0d\x0a public function execute_dql($sql){ \x0d\x0a $res=mysql_query($sql,$this-conn); \x0d\x0a return $res; \x0d\x0a } \x0d\x0a //執(zhí)行增填改語句 \x0d\x0a public function execute_dml($sql){ \x0d\x0a $b=mysql_query($sql,$this-conn); \x0d\x0a if(!$b){ \x0d\x0a return 3; \x0d\x0a }else{ \x0d\x0a if(mysql_affected_rows($this-conn)){ \x0d\x0a return 1;//表示OK \x0d\x0a }else{ \x0d\x0a return 2;//表示沒有行收到影響 \x0d\x0a } \x0d\x0a } \x0d\x0a }\x0d\x0a}
創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括榆樹網(wǎng)站建設(shè)、榆樹網(wǎng)站制作、榆樹網(wǎng)頁制作以及榆樹網(wǎng)絡(luò)營(yíng)銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,榆樹網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到榆樹省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!
本文實(shí)例講述了PHP基于單例模式實(shí)現(xiàn)的數(shù)據(jù)庫操作基類。分享給大家供大家參考,具體如下:
配置文件:
?php
$db
=
array(
'host'='localhost',
'user'='root',
'password'='',
'database'='test',
)
?
php
數(shù)據(jù)庫基類:
?php
class
db
{
public
$conn;
public
static
$sql;
public
static
$instance=null;
private
function
__construct(){
require_once('db.config.php');
$this-conn
=
mysql_connect($db['host'],$db['user'],$db['password']);
if(!mysql_select_db($db['database'],$this-conn)){
echo
"失敗";
};
mysql_query('set
names
utf8',$this-conn);
}
public
static
function
getInstance(){
if(is_null(self::$instance)){
self::$instance
=
new
db;
}
return
self::$instance;
}
/**
*
查詢數(shù)據(jù)庫
*/
public
function
select($table,$condition=array(),$field
=
array()){
$where='';
if(!empty($condition)){
foreach($condition
as
$k=$v){
$where.=$k."='".$v."'
and
";
}
$where='where
'.$where
.'1=1';
}
$fieldstr
=
'';
if(!empty($field)){
foreach($field
as
$k=$v){
$fieldstr.=
$v.',';
}
$fieldstr
=
rtrim($fieldstr,',');
}else{
$fieldstr
=
'*';
}
self::$sql
=
"select
{$fieldstr}
from
{$table}
{$where}";
$result=mysql_query(self::$sql,$this-conn);
$resuleRow
=
array();
$i
=
0;
while($row=mysql_fetch_assoc($result)){
foreach($row
as
$k=$v){
$resuleRow[$i][$k]
=
$v;
}
$i++;
}
return
$resuleRow;
}
/**
*
添加一條記錄
*/
public
function
insert($table,$data){
$values
=
'';
$datas
=
'';
foreach($data
as
$k=$v){
$values.=$k.',';
$datas.="'$v'".',';
}
$values
=
rtrim($values,',');
$datas
=
rtrim($datas,',');
self::$sql
=
"INSERT
INTO
{$table}
({$values})
VALUES
({$datas})";
if(mysql_query(self::$sql)){
return
mysql_insert_id();
}else{
return
false;
};
}
/**
*
修改一條記錄
*/
public
function
update($table,$data,$condition=array()){
$where='';
if(!empty($condition)){
foreach($condition
as
$k=$v){
$where.=$k."='".$v."'
and
";
}
$where='where
'.$where
.'1=1';
}
$updatastr
=
'';
if(!empty($data)){
foreach($data
as
$k=$v){
$updatastr.=
$k."='".$v."',";
}
$updatastr
=
'set
'.rtrim($updatastr,',');
}
self::$sql
=
"update
{$table}
{$updatastr}
{$where}";
return
mysql_query(self::$sql);
}
/**
*
刪除記錄
*/
public
function
delete($table,$condition){
$where='';
if(!empty($condition)){
foreach($condition
as
$k=$v){
$where.=$k."='".$v."'
and
";
}
$where='where
'.$where
.'1=1';
}
self::$sql
=
"delete
from
{$table}
{$where}";
return
mysql_query(self::$sql);
}
public
static
function
getLastSql(){
echo
self::$sql;
}
}
$db
=
db::getInstance();
//$list
=
$db-select('demo',array('name'='tom','password'='ds'),array('name','password'));
//echo
$db-insert('demo',array('name'='腳本之家','password'='123'));
//echo
$db-update('demo',array("name"='xxx',"password"='123'),array('id'=1));
echo
$db-delete('demo',array('id'='2'));
db::getLastSql();
echo
"pre";
?
更多關(guān)于PHP操作數(shù)據(jù)庫相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php+mysql數(shù)據(jù)庫操作入門教程》、《PHP基于pdo操作數(shù)據(jù)庫技巧總結(jié)》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
我也不是老手,,呵
首先,,數(shù)據(jù)庫配置信息,,dbhost,dbport,dbuser,dbpass,dbname,charset這些參數(shù)最好不要設(shè)成全局變量,而從構(gòu)造函數(shù)傳遞...
這樣做的好處有幾點(diǎn)
這個(gè)類可以單獨(dú)調(diào)用,,?不用再包含配置文件,,因?yàn)槟阏{(diào)用類的php文件一定會(huì)先包含配置文件,,再包含數(shù)據(jù)庫操作類,,
通過參數(shù)傳遞可以提高類的獨(dú)立性,,這樣,,以后這個(gè)類可以被移植到任何系統(tǒng)里面調(diào)用,,,
1、取得結(jié)果集中字段的數(shù)目
這個(gè)是由你select?后面的東西來決定的,,如果你用的是select?*
你已經(jīng)寫了這個(gè)
$result=mysql_query($str."?limit?".$rows)or?die(mysql_error());
$count=0;
$data=array();
while($rs=mysql_fetch_row($result)){
$data[$count]=$rs;
$count++;
}
@mysql_free_result($result);
return?$result;
你可以在這段代碼@mysql_free_result($result);之前,,用count($data[0])函數(shù)來提取,,,你這里的return?$result是什么意思,,不是已經(jīng)釋放了嗎,,應(yīng)該是return?$data才對(duì)
$result=mysql_query($str."?limit?".$rows)or?die(mysql_error());
這一句你是限制提取條數(shù),,,但這在實(shí)際工作中沒有什么用處,,,
一般的分頁語句都是寫在sql里面的limit?x,xx;這樣
你這樣寫,,如果有1W條記錄,,你就沒辦法從數(shù)據(jù)庫的角度去分類
第二個(gè)也是一樣的
因?yàn)槟愕腟electRows($str,$rows)返回的是一個(gè)二維數(shù)組,,所以要知道有多少條記錄,,,只要用count($data)就可以知道..
$db=new?mysqlconn();
$str="SELECT?*?FROM?xxx?ORDER?BY?XXX?ASC";
$data=$db-SelectRows($str,$rows);
$counts=count($data);//這就是取得的總記錄數(shù)
我也剛剛學(xué)PHP,正在研究中,雖然你只給10分........
首先,將代碼保存到一個(gè)文件,如:mysql.class.php
其次,在一個(gè)常用的文件里調(diào)用:比如頭部文件header.php,因?yàn)槲曳旁诟夸浰杂孟旅娣绞綄?dǎo)入其他文件:
require dirname(__FILE__) . 'include/config.php';
//導(dǎo)入類文件
require dirname(__FILE__) . 'include/mysql.class.php';
//定義一個(gè)類及初始化數(shù)據(jù)庫類
$db = new mysql($db_host, $db_user, $db_pass, $db_name);
$db_host = $db_user = $db_pass = $db_name = NULL;
然后,在test.php文件調(diào)用:
require_once dirname(__FILE__) . '/header.php';
使用方法:
$sql = "讀取表";
$res = $db-query($sql);
$info = array();//定義數(shù)組
while($row=$db-fetchRow($res))
{
$arr['id'] = $row['id'];
$arr['title'] = $row['title'];
$info[] = $arr;
}
可以在顯示的地方用:
foreach($info as $i)
{
echo $i['title']."br /";
}
或是直接使用while
還用另一種調(diào)用方式:
$here_area = $db-getRow("select areaid,areaname from {$table}area where areaid='$areaid'");
$here[] = array('name'=$here_area['areaname'],'id'=$here_area['areaid']);
測(cè)試通過,因?yàn)槲艺谑褂?....................................
config.php代碼:
?php
$db_host = "localhost";
$db_name = "test";
$db_user = "root";
$db_pass = "";
$table = "mini_";
$charset = "gb2312";
$dbcharset = "gbk";
?
mysql.class.php代碼:
?php
class mysql
{
var $link = NULL;
//自動(dòng)執(zhí)行__construct php5類構(gòu)建方法,如果PHP4和PHP5同時(shí)使用會(huì)自動(dòng)使用PHP5的方法
function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $quiet = 0)
{
//自動(dòng)執(zhí)行時(shí)調(diào)用mysql函數(shù)
$this-mysql($dbhost, $dbuser, $dbpw, $dbname, $pconnect, $quiet);
}
//php4類構(gòu)建方法,如果沒有 __construct 就自動(dòng)執(zhí)行此功能
function mysql($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $quiet = 0)
{
if ($quiet)
{
$this-connect($dbhost, $dbuser, $dbpw, $dbname, $pconnect, $quiet);
}
else
{
$this-settings = array(
'dbhost' = $dbhost,
'dbuser' = $dbuser,
'dbpw' = $dbpw,
'dbname' = $dbname,
'charset' = $charset,
'pconnect' = $pconnect
);
}
}
function connect($dbhost, $dbuser, $dbpw, $dbname = '', $pconnect = 0, $quiet = 0)
{
global $dbcharset;
if ($pconnect)
{
if (!($this-link = @mysql_pconnect($dbhost, $dbuser, $dbpw)))
{
if (!$quiet)
{
$this-ErrorMsg("Can't pConnect MySQL Server($dbhost)!");
}
return false;
}
}
else
{
if (PHP_VERSION = '4.2')
{
$this-link = @mysql_connect($dbhost, $dbuser, $dbpw, true);
}
else
{
$this-link = @mysql_connect($dbhost, $dbuser, $dbpw);
mt_srand((double)microtime() * 1000000);
}
if (!$this-link)
{
if (!$quiet)
{
$this-ErrorMsg("Can't Connect MySQL Server($dbhost)!");
}
return false;
}
}
$this-dbhash = md5($this-root_path . $dbhost . $dbuser . $dbpw . $dbname);
$this-version = mysql_get_server_info($this-link);
if ($this-version '4.1')
{
if ($dbcharset != 'latin1')
{
mysql_query("SET character_set_connection=$dbcharset, character_set_results=$dbcharset, character_set_client=binary", $this-link);
}
if ($this-version '5.0.1')
{
mysql_query("SET sql_mode=''", $this-link);
}
}
if ($dbname)
{
if (mysql_select_db($dbname, $this-link) === false )
{
if (!$quiet)
{
$this-ErrorMsg("Can't select MySQL database($dbname)!");
}
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
function query($sql, $type = '')
{
if ($this-link === NULL)
{
$this-connect($this-settings['dbhost'], $this-settings['dbuser'], $this-settings['dbpw'], $this-settings['dbname'], $this-settings['charset'], $this-settings['pconnect']);
$this-settings = array();
}
if ($this-queryCount++ = 99)
{
$this-queryLog[] = $sql;
}
if ($this-queryTime == '')
{
if (PHP_VERSION = '5.0.0')
{
$this-queryTime = microtime(true);
}
else
{
$this-queryTime = microtime();
}
}
if (!($query = mysql_query($sql, $this-link)) $type != 'SILENT')
{
$this-error_message[]['message'] = 'MySQL Query Error';
$this-error_message[]['sql'] = $sql;
$this-error_message[]['error'] = mysql_error($this-link);
$this-error_message[]['errno'] = mysql_errno($this-link);
$this-ErrorMsg();
return false;
}
return $query;
}
function affected_rows()
{
return mysql_affected_rows($this-link);
}
function num_fields($query)
{
return mysql_num_fields($query);
}
function error()
{
return mysql_error($this-link);
}
function errno()
{
return mysql_errno($this-link);
}
function num_rows($query)
{
return mysql_num_rows($query);
}
function insert_id()
{
return mysql_insert_id($this-link);
}
function fetchRow($query)
{
return mysql_fetch_assoc($query);
}
function fetcharray($query)
{
return mysql_fetch_array($query);
}
function version()
{
return $this-version;
}
function close()
{
return mysql_close($this-link);
}
function ErrorMsg($message = '', $sql = '')
{
if ($message)
{
echo "$message\n\n";
}
else
{
echo "bMySQL server error report:";
print_r($this-error_message);
}
exit;
}
function getCol($sql)
{
$res = $this-query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_row($res))
{
$arr[] = $row[0];
}
return $arr;
}
else
{
return false;
}
}
function getOne($sql, $limited = false)
{
if ($limited == true)
{
$sql = trim($sql . ' LIMIT 1');
}
$res = $this-query($sql);
if ($res !== false)
{
$row = mysql_fetch_row($res);
if ($row !== false)
{
return $row[0];
}
else
{
return '';
}
}
else
{
return false;
}
}
function getAll($sql)
{
$res = $this-query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_assoc($res))
{
$arr[] = $row;
}
return $arr;
}
else
{
return false;
}
}
//使用: getRow($sql,true) 如果有true那值是 limit 1,讀取一條信息
function getRow($sql, $limited = false)
{
if ($limited == true)
{
$sql = trim($sql . ' LIMIT 1');
}
$res = $this-query($sql);
if ($res !== false)
{
return mysql_fetch_assoc($res);
}
else
{
return false;
}
}
}
?