Home >Backend Development >PHP Tutorial >php mysql database class (php novice introduction)

php mysql database class (php novice introduction)

WBOY
WBOYOriginal
2016-07-25 09:01:001063browse
  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. }

复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn