当前位置:Gxlcms > PHP教程 > phpmysql数据库类(php新手入门)

phpmysql数据库类(php新手入门)

时间:2021-07-01 10:21:17 帮助过:18人阅读

  1. //by http://bbs.it-home.org

  2. class mySql{
  3. private $result;
  4. private $conn;
  5. public static $hasNew = false;
  6. private __construct(){}
  7. function __destruct(){
  8. self::$hasnew=false;
  9. }

  10. function doNew(){

  11. if(self::$have_new){
  12. exit('数据库只能连接一次!');
  13. }else{
  14. self::$hasNew=true;
  15. return new self;
  16. }
  17. }
  18. private function connect($host,$user,$password,$dbname,$charset='utf8'){
  19. $this->conn = mysql_connect($host,$user,$password) or exit('错误码:'.mysql_errno(). '数据库连接失败:'.mysql_error());
  20. mysql_select_db($dbname,$this->conn) or exit('错误码:'.mysql_errno().'选择数据库失败:'.mysql_error());
  21. mysql_query("set names $charset",$this->conn);
  22. }

  23. function query($sql,$buffer=true){

  24. //mysql_real_escape_string($sql,$this->conn);//特殊字符义
  25. if($buffer){
  26. $this->result=mysql_query($sql,$this->conn) or exit('错误码:'.mysql_errno().'sql语句执行失败:'.mysql_error());
  27. }else{
  28. $this->result=mysql_unbuffered_query($sql,$this->conn) or exit('错误码:'.mysql_errno().'sql语句执行失败:'.mysql_error());
  29. }
  30. }
  31. function getRecord(){
  32. return mysql_fetch_array($this->result);
  33. }
  34. function close(){
  35. mysql_free_result($this->result);
  36. mysql_close($this->conn);
  37. }

  38. }

2、调用示例

  1. //数据库

  2. $db_host='localhost';
  3. $db_user='root';
  4. $db_pwd='root';
  5. $db_name='news';
  6. $charset='utf8';
  7. $sql="select * from news_base";

  8. $db=mySql::doNew();

  9. $db->connect($db_host,$db_user,$db_pwd,$db_name,$charset='utf8');
  10. $db->query($sql);
  11. while($row=$db->getRecord()){
  12. echo $row[1].'
    ';
  13. }

人气教程排行