phpmysql数据库类(php新手入门)
时间:2021-07-01 10:21:17
帮助过:18人阅读
//by http://bbs.it-home.org - class mySql{
- private $result;
- private $conn;
- public static $hasNew = false;
-
- private __construct(){}
- function __destruct(){
- self::$hasnew=false;
- }
function doNew(){ - if(self::$have_new){
- exit('数据库只能连接一次!');
- }else{
- self::$hasNew=true;
- return new self;
- }
- }
-
- private function connect($host,$user,$password,$dbname,$charset='utf8'){
- $this->conn = mysql_connect($host,$user,$password) or exit('错误码:'.mysql_errno(). '数据库连接失败:'.mysql_error());
- mysql_select_db($dbname,$this->conn) or exit('错误码:'.mysql_errno().'选择数据库失败:'.mysql_error());
- mysql_query("set names $charset",$this->conn);
- }
function query($sql,$buffer=true){ - //mysql_real_escape_string($sql,$this->conn);//特殊字符义
- if($buffer){
- $this->result=mysql_query($sql,$this->conn) or exit('错误码:'.mysql_errno().'sql语句执行失败:'.mysql_error());
- }else{
- $this->result=mysql_unbuffered_query($sql,$this->conn) or exit('错误码:'.mysql_errno().'sql语句执行失败:'.mysql_error());
- }
- }
-
- function getRecord(){
- return mysql_fetch_array($this->result);
- }
-
- function close(){
- mysql_free_result($this->result);
- mysql_close($this->conn);
- }
}
2、调用示例
//数据库 - $db_host='localhost';
- $db_user='root';
- $db_pwd='root';
- $db_name='news';
- $charset='utf8';
- $sql="select * from news_base";
$db=mySql::doNew(); - $db->connect($db_host,$db_user,$db_pwd,$db_name,$charset='utf8');
- $db->query($sql);
- while($row=$db->getRecord()){
- echo $row[1].'
'; - }
|