简单的PHP数据库操作类

初学PHP,代码不够严谨的地方,希望给提出,大家共同交流学习!

 

 

<?php
/**
 * 数据库操作类
 * last edit: 2010-1-11
 
*/

 
class mysql{
     
private $db_host;
     
private $db_uname;
     
private $db_pass;
     
private $db_dbname;
     
private $db_codeing;
     
private $conn;
     
private $result;
     
     
     
public function __construct($host,$uname,$pass,$dbname,$codeing){
         
$this->db_host   =    $host;
         
$this->db_uname  =    $uname;
         
$this->db_pass   =    $pass;
         
$this->db_dbname =    $dbname;
         
$this->db_codeing=    $codeing;
         
$this->connect();
         
     }
     
     
/**
      * 构造函数,建立数据库连接
      * 主机,用户名,密码,数据库名
      
*/
     
private function connect(){
         
$this->conn = @mysql_connect($this->db_host,$this->db_uname,$this->db_pass,$this->db_dbname,$this->db_codeing);
         
if ($this->conn != true){
             
$this->showMsg("连接 数据库建立失败。你的用户名、主机或密码不正确");
         }
         
if (@mysql_select_db($this->db_dbname) != true ){
             
$this->showMsg("找不到数据库:".$this->db_dbname);
         }
         @
mysql_query("SET NAMES $this->db_codeing");
     }
     
     
public function query($sql){
         
if ( empty($sql) ){
             
$this->showMsg("SQL语句不存在");
         }
         
$this->result = @mysql_query($sql);
         
if ($this->result != true){
             
$this->showMsg("无效的SQL语句:".$sql);
         }
     }
     
     
/**
      * 循环输出查询结果集
      *
      
*/
     
public function fetcharray(){
         
$v=array();
         
if ($this->result){
             
while (($rs=mysql_fetch_array($this->result))!=false){
                 
$v[]=$rs;
             }
         }
         
return $v;
     }
     
     
public function fetchone(){
         
return @mysql_fetch_array($this->result);
     }
     
     
/**
      * 获得符合查询要求的总数量
      *
      
*/
     
public function getrow(){
         
return @mysql_num_rows($this->result);
     }
     
     
/**
      * 错误信息提示
      *
      * @param msg=要输出错误信息
      
*/
     
public function showMsg($msg=''){
         
echo("<br>");
         
echo("<font color='#red'><strong>出现错误:</strong></font>");
         
echo("<font color='#blue'>".$msg."</font>");
         
exit();
     }
 }

 
/**循环调用方法*/
 
$db = new mysql('主机','用户名','密码','数据库名','数据库编码');
 
$db->query("select * from info_type");
 
$rs = $db->fetcharray();
 
foreach ($rs as $newrs){
     
echo($newrs['info_typetitle']."<br />");
 }
 
echo($db->getrow());
 
 
 
?>

 

 

posted @ 2010-01-11 14:58  醉情僧  阅读(441)  评论(0)    收藏  举报