欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

完整的PHP操作MySQL数据库类

程序员文章站 2022-04-24 14:38:33
...
  1. class database
  2. {
  3. private $hostname;
  4. private $user;
  5. private $pass;
  6. private $dbname;
  7. private $linkflag;
  8. private $charset;
  9. function __construct()
  10. {
  11. $this->hostname="localhost";
  12. $this->user="root";
  13. $this->pass="111";
  14. $this->dbname="";
  15. $this->charset="utf8"; //gb2312 GBK utf8
  16. $this->linkflag=mysql_connect($this->hostname,$this->user,$this->pass);
  17. mysql_select_db($this->dbname,$this->linkflag) or die($this->error());
  18. mysql_query("set names ".$this->charset);
  19. }
  20. function __set($property_name,$value)
  21. {
  22. return $this->$property_name=$value;
  23. }
  24. function __get($property_name)
  25. {
  26. if(isset($this->$property_name))
  27. {
  28. return $this->$property_name;
  29. }
  30. else return null;
  31. }
  32. function __call($function_name, $args)
  33. {
  34. echo "
    你所调用的方法 $function_name 不存在
    \n";
  35. }
  36. function query($sql)
  37. {
  38. $res=mysql_query($sql) or die($this->error());
  39. return $res;
  40. }
  41. function fetch_array($res)
  42. {
  43. return mysql_fetch_array($res);
  44. }
  45. function fetch_object($res)
  46. {
  47. return mysql_fetch_object($res);
  48. }
  49. function fetch_obj_arr($sql)
  50. {
  51. $obj_arr=array();
  52. $res=$this->query($sql);
  53. while($row=mysql_fetch_object($res))
  54. {
  55. $obj_arr[]=$row;
  56. }
  57. return $obj_arr;
  58. }
  59. function error()
  60. {
  61. if($this->linkflag)
  62. {
  63. return mysql_error($this->linkflag);
  64. }
  65. else return mysql_error();
  66. }
  67. function errno()
  68. {
  69. if($this->linkflag)
  70. {
  71. return mysql_errno($this->linkflag);
  72. }
  73. else return mysql_errno();
  74. }
  75. function affected_rows()
  76. {
  77. return mysql_affected_rows($this->linkflag);
  78. }
  79. function num_rows($sql)
  80. {
  81. $res=$this->execute($sql);
  82. return mysql_num_rows($res);
  83. }
  84. function num_fields($res)
  85. {
  86. return mysql_num_fields($res);
  87. }
  88. function insert_id()
  89. {
  90. $previous_id=mysql_insert_id($this->linkflag);
  91. return $previous_id;
  92. }
  93. function result($res,$row,$field=null)
  94. {
  95. if($field===null)
  96. {
  97. $res=mysql_result($res,$row);
  98. }
  99. else $res=mysql_result($res,$row,$field);
  100. return $res;
  101. }
  102. function version()
  103. {
  104. return mysql_get_server_info($this->linkflag);
  105. }
  106. function data_seek($res,$rowNum)
  107. {
  108. return mysql_data_seek($res,$rowNum);
  109. }
  110. function __destruct()
  111. {
  112. //mysql_close($this->linkflag);
  113. }
  114. }
  115. ?>
复制代码

数据库类, PHP, MySQL