Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Db
- {
- private $link;
- private $host = 'localhost';
- private $user = 'root';
- private $password = '';
- private $database = 'oop';
- private $table = 'users';
- //Подключается к базе:
- public function __construct()
- {
- $this->link = mysqli_connect($this->host, $this->user, $this->password, $this->database );
- }
- //Делает запрос к базе:
- public function get($id, $field)
- {
- $query = $this->createSelect($id, $field);
- $result = $this->makeQuery($query); //будет в виде ['age'=>25]
- return $result[$field]; //а тут достанем 25
- }
- //Создает строку с запросом:
- private function createSelect($id, $field)
- {
- $table = $this->table;
- return "SELECT $field FROM $table WHERE id=$id";
- }
- //Совершает запрос к базе:
- private function makeQuery($query)
- {
- $result = mysqli_query($this->link, $query);
- return mysqli_fetch_assoc($result);
- }
- }
- $bazaDan = new Db;
- echo $bazaDan->get('1', 'name');
- echo '<br>';
- class User
- {
- private $id;
- private $db;
- public function __construct($id)
- {
- $this->id = $id;
- //Создаем объект для работы с БД:
- $this->db = new Db;
- }
- public function getName()
- {
- return $this->db->get($this->id, 'name');
- }
- public function getAge()
- {
- return $this->db->get($this->id, 'age');
- }
- }
- $user = new User('1');
- echo $user->getName();
- echo '<br>';
- echo $user->getAge();
- ?>
Add Comment
Please, Sign In to add comment