php连接mysql数据库的实用类

这是一款非常完整理的php连接mysql数据库,利用了php与mysql数据库进行连接,好了费话不说多了来看看这款经典的连接数据库代码是不是你想要找的吧,代码如下:

  1. class mysql {
  2. var $linkid=null;
  3. function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = 'gbk', $connect = 1) {
  4. $this -> connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $connect);
  5. }
  6. function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = 'gbk', $connect=1){
  7. $func = emptyempty($connect) ? 'mysql_pconnect' : 'mysql_connect';
  8. if(!$this->linkid = @$func($dbhost, $dbuser, $dbpw, true)){
  9. $this->dbshow('can not connect to mysql!');
  10. } else {
  11. if($this->dbversion() > '4.1'){
  12. mysql_query( "set names gbk");
  13. if($this->dbversion() > '5.0.1'){
  14. mysql_query("set sql_mode = ''",$this->linkid);
  15. }
  16. }
  17. }
  18. if($dbname){
  19. if(mysql_select_db($dbname, $this->linkid)===false){
  20. $this->dbshow("can't select mysql database($dbname)!");
  21. }
  22. }
  23. }
  24. function select_db($dbname){
  25. return mysql_select_db($dbname, $this->linkid);
  26. }
  27. function query($sql){
  28. if(!$query=@mysql_query($sql, $this->linkid)){
  29. $this->dbshow("query error:$sql");
  30. }else{
  31. return $query;
  32. }
  33. }
  34. function getall($sql, $type=mysql_assoc){
  35. $query = $this->query($sql);
  36. while($row = mysql_fetch_array($query,$type)){
  37. $rows[] = $row;
  38. }
  39. return $rows;
  40. }
  41. function getone($sql, $type=mysql_assoc){
  42. $query = $this->query($sql,$this->linkid);
  43. $row = mysql_fetch_array($query, $type);
  44. return $row;
  45. }
  46. function fetch_array($result,$type = mysql_assoc){
  47. return mysql_fetch_array($result);
  48. }
  49. function affected_rows(){
  50. return mysql_affected_rows($this->linkid);
  51. }
  52. function num_rows(){
  53. return mysql_num_rows($this->linkid);
  54. }
  55. function num_fields($result){
  56. return mysql_num_fields($result);
  57. }
  58. function insert_id(){
  59. return mysql_insert_id($this->linkid);
  60. }
  61. function free_result(){
  62. return mysql_free_result($this->linkid);
  63. }
  64. function error(){
  65. return mysql_error($this->linkid);
  66. }
  67. function errno(){
  68. return mysql_errno($this->linkid);
  69. }
  70. function close(){
  71. return mysql_close($this->linkid);
  72. }
  73. function dbversion(){
  74. return mysql_get_server_info($this->linkid);
  75. }
  76. function dbshow($msg){
  77. if($msg){
  78. echo "error:".$msg."<br><br>";
  79. }else{
  80. echo "errno:".$this->errno()."<br>error:".$this->error();
  81. }//开源代码phpfensi.com
  82. exit;
  83. }
  84. }