Home > Backend Development > PHP Tutorial > PHP class for operating MySQL database

PHP class for operating MySQL database

WBOY
Release: 2016-07-25 09:06:28
Original
988 people have browsed it
PHP class that operates mysql database
  1. ///////////////////Database connection class//////////////////// /
  2. class connect{
  3. private $host;//Host name
  4. private $name;//Username
  5. private $pass;//Password
  6. private $conn;//Connection handle name
  7. private $db;//Database handle Name
  8. private $dbname;//Database name
  9. //====================================== ===============================
  10. function open($addr,$dbuser,$psw){//Connect to the host
  11. $this->host=$addr;
  12. $this->name=$dbuser;
  13. $this->pass=$psw;
  14. $this->conn=mysql_connect($this->host,$ this->name,$this->pass);
  15. }
  16. function opendb($database,$charset){//Connect to the database
  17. $this->dbname=$database;
  18. mysql_query("set names " .$charset);//Set the character set
  19. $this->db=mysql_select_db($this->dbname,$this->conn);
  20. }
  21. function close(){//Close the host connection
  22. mysql_close ($this->conn);
  23. }
  24. //==================================== ================================
  25. function __construct($addr,$dbuser,$psw){
  26. $this ->open($addr, $dbuser, $psw);
  27. }
  28. function __toString(){
  29. if($this->conn){
  30. $msg= "User".$this->name. "Login to the host successfully.";
  31. }else {
  32. $msg= "User ".$this->name." failed to log in to the host. ";
  33. }
  34. if($this->db){
  35. $msg.= "Connection to ".$this->dbname." database was successful. ";
  36. }else{
  37. $msg.= "Link ".$this->dbname." Database failed. ";
  38. }
  39. return $msg;
  40. }
  41. function __call($n,$v){//Error method absorption
  42. return "Does not exist".$n."() method";
  43. }
  44. }
  45. /////////////////Example/////////////////////
  46. // $db=new connect(" localhost", "root", "lijun");
  47. // $db->opendb("message", "utf8");
  48. // echo $db;
  49. // $db->close ();
  50. // $db->open("localhost","root","lijun");
  51. // $db->opendb("message", "utf8");
  52. / / echo $db->ji("er");
  53. ?>
Copy code


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template