Guest User

Untitled

a guest
Nov 26th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. <?php
  2. class Db
  3. {
  4. private $link;
  5. private $host = 'localhost';
  6. private $user = 'root';
  7. private $password = '';
  8. private $database = 'oop';
  9. private $table = 'users';
  10.  
  11. //Подключается к базе:
  12. public function __construct()
  13. {
  14. $this->link = mysqli_connect($this->host, $this->user, $this->password, $this->database );
  15. }
  16.  
  17. //Делает запрос к базе:
  18. public function get($id, $field)
  19. {
  20. $query = $this->createSelect($id, $field);
  21. $result = $this->makeQuery($query); //будет в виде ['age'=>25]
  22. return $result[$field]; //а тут достанем 25
  23. }
  24.  
  25. //Создает строку с запросом:
  26. private function createSelect($id, $field)
  27. {
  28. $table = $this->table;
  29. return "SELECT $field FROM $table WHERE id=$id";
  30. }
  31.  
  32. //Совершает запрос к базе:
  33. private function makeQuery($query)
  34. {
  35. $result = mysqli_query($this->link, $query);
  36. return mysqli_fetch_assoc($result);
  37. }
  38. }
  39.  
  40. $bazaDan = new Db;
  41.  
  42. echo $bazaDan->get('1', 'name');
  43. echo '<br>';
  44.  
  45.  
  46. class User
  47. {
  48. private $id;
  49. private $db;
  50.  
  51. public function __construct($id)
  52. {
  53. $this->id = $id;
  54.  
  55. //Создаем объект для работы с БД:
  56. $this->db = new Db;
  57. }
  58.  
  59. public function getName()
  60. {
  61. return $this->db->get($this->id, 'name');
  62. }
  63.  
  64. public function getAge()
  65. {
  66. return $this->db->get($this->id, 'age');
  67. }
  68.  
  69. }
  70.  
  71. $user = new User('1');
  72.  
  73. echo $user->getName();
  74. echo '<br>';
  75. echo $user->getAge();
  76.  
  77. ?>
Add Comment
Please, Sign In to add comment