在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

数据库操作的model类,用到了__call方法

2016-12-20 13:14| 发布者: zhangjf| 查看: 486| 评论: 0

摘要: 实现了数据的查找 ? /* 作者 : shyhero 邮箱 : shyhero@outlook.com Q Q : 1757424878 */ define(HOSTNAME,127.0.0.1); define(USERNAME,root); define(PASSWORD,); define(DATANAME,class) ...
实现了数据的查找
  1. <?
  2. /*
  3. 作者 : shyhero
  4. 邮箱 : shyhero@outlook.com
  5. Q Q : 1757424878
  6. */
  7. define("HOSTNAME","127.0.0.1");
  8. define("USERNAME","root");
  9. define("PASSWORD","");
  10. define("DATANAME","class");
  11. class Model{
  12. private $link;
  13. private $tableName;
  14. private $zd;
  15. private $method = array(
  16. "where" => "",
  17. "order" => "",
  18. "limit" => "",
  19. "group" => "",
  20. "having" => ""
  21. );
  22. public function __construct($tableName){
  23. $this -> tableName = $tableName;
  24. try{
  25. $this -> link = mysqli_connect(HOSTNAME,USERNAME,PASSWORD,DATANAME);
  26. mysqli_set_charset($this -> link,"UTF8");
  27. }catch(Exception $e){
  28. echo "数据库连接失败";
  29. }
  30. $this -> desc();
  31. }
  32. public function __destruct(){
  33. mysqli_close($this -> link);
  34. }
  35. public function desc(){
  36. $sql = " desc {$this -> tableName}; ";
  37. $res = mysqli_query($this -> link,$sql);
  38. $arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
  39. for($i = 0 ;$i < count($arr);$i++){
  40. $brr[] = $arr[$i]['Field'];
  41. }
  42. $this -> zd = $brr;
  43. return $brr;
  44. }
  45. public function __call($name,$value){
  46. $name = strtolower($name);
  47. if(array_key_exists($name,$this -> method)){
  48. if($name == 'order'){
  49. $this -> method['order'] = " order by ".$value[0];
  50. }elseif($name == 'group'){
  51. $this -> method['group'] = " group by ".$value[0];
  52. }else{
  53. $this -> method[$name] = " {$name} ".$value[0];
  54. }
  55. }else{
  56. return "the method is not found!";
  57. }
  58. return $this;
  59. }
  60. public function method(){
  61. return " {$this -> method['where']} {$this -> method['order']} {$this -> method['limit']} {$this -> method['group']} {$this -> method['having']}; ";
  62. }
  63. public function find($a="*"){
  64. if(in_array("{$a}",$this -> zd) || $a == "*"){
  65. $sql = "select {$a} from {$this -> tableName} {$this -> method()} ";
  66. }else{
  67. $sql = "select * from {$this -> tableName}";
  68. }
  69. //return $sql;
  70. $res = mysqli_query($this -> link,$sql);
  71. $arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
  72. return $arr;
  73. }
  74. }
复制代码
  1. <?
  2. function __autoload($className){
  3. require($className.".class.php");
  4. }
  5. $a = new Model("stu");
  6. $a -> where("name = 'zhu'")->limit("5,10");
  7. var_dump($a -> find("name"));
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 07:17

Copyright 2015-2025 djqfx

返回顶部