当前位置:Gxlcms > 数据库问题 > [我在学php之三]Po上自己写的数据库类,方便以后进行查找。

[我在学php之三]Po上自己写的数据库类,方便以后进行查找。

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

  1. <code>
  2. class mysql{
  3. private $conn; //私有化 变量$conn
  4. private $db_host; //主机
  5. private $db_user;
  6. private $db_password;
  7. private $db_name; //数据库名称
  8. function __construct($db_host,$db_user,$db_password,$db_name){
  9. //构造函数,传入 类中的connect函数中
  10. $this->db_host = $db_host;
  11. $this->db_user = $db_user;
  12. $this->db_password = $db_password;
  13. $this->db_name = $db_name;
  14. $this->connect();
  15. }
  16. function connect(){
  17. //数据库连接函数
  18. $this->conn = mysql_connect($this->db_host,$this->db_user,$this->db_password) or die("数据库连接失败".mysql_errno().":".mysql_error());
  19. mysql_select_db($this->db_name,$this->conn) or die(‘打开数据库失败‘).mysql_error();
  20. mysql_set_charset(‘utf8‘);
  21. return $this->conn;
  22. }
  23. //插入数据库,$table(数据库名称),$array
  24. function insert($table,$array){
  25. $keys = "`".implode("`,`", array_keys($array))."`"; //调取数组中的键值
  26. $vals = "‘".implode("‘,‘", array_values($array))."‘"; //调去数组中的数值
  27. $sql = "insert into {$table} ({$keys}) values({$vals})";
  28. $query = mysql_query($sql);
  29. return mysql_insert_id();
  30. }
  31. //删除指定数据
  32. function delete($table,$id,$where=null){
  33. //语句: delete from table where id = ....
  34. $where = $where ==null?null:‘where ‘.$where;
  35. $sql = "delete from {$table} where id = {$id} limit 1";
  36. $query = mysql_query($sql);
  37. return $query;
  38. }
  39. //选择数据库
  40. public function select($table,$array,$where=null){
  41. //语句: select * from table where `user`=‘$user‘......
  42. foreach ($array as $key => $value) {
  43. $select[] = ‘`‘.$key.‘`=‘.$value;
  44. }
  45. $select = implode(‘ and ‘, $select);
  46. $where = $where == null?null:$where;
  47. $sql = "select * from {$table} where ".$select.‘ ‘.$where;
  48. return $sql;
  49. }
  50. //修改数据库
  51. function update($table,$array,$where = null){
  52. //语句: update table set `name`=‘kopa‘ where id = ....
  53. foreach ($array as $key => $value) {
  54. $string[] = ‘`‘.$key.‘`=‘.$value;
  55. }
  56. $string =implode(‘`,‘,$string);
  57. $where = $where==null?null:" where ".$where;
  58. $sql = "update {$table} set ".$string.$where;
  59. return $sql;
  60. // $query = mysql_query($sql);
  61. // return $query;
  62. // print_r("update {$table} set ".$string.$where);
  63. }
  64. //读取数据库总行数 mysql_num_row
  65. function totalRow($sql){
  66. $query = mysql_query($sql);
  67. $result = mysql_num_rows($query);
  68. return $result;
  69. }
  70. //读取数据库的数组
  71. function fetch_array($sql){
  72. $query = mysql_query($sql);
  73. $res = mysql_fetch_array($query);
  74. return $res;
  75. }
  76. }
  77. $db = new mysql("localhost",‘root‘,‘3363064‘,‘ctxy‘);
  78. </code>

[我在学php之三]Po上自己写的数据库类,方便以后进行查找。

标签:

人气教程排行