I can not figure it out, made a connection to the database, checked, everything works, checked by a request to add a row to the database (the line added, everything works). Here is my code

***index.php*** require_once("../includes/database.php"); require_once("../includes/users.php"); if(isset ($database)) {echo"true";}else {echo "false";} $sql = "SELECT * FROM users WHERE id = 1"; $result_set = $database->query($sql); $found_user = $database->fetch_array($result_set); echo $found_user['username']; echo "<hr />"; $found_user = User::find_by_id(1); echo $found_user['username']; echo "<hr />"; $user_set = User::find_all(); while ($user = $database->fetch_array($user_set)) { echo "User: ". $user['username'] ."<br />"; echo "Name: ". $user['first_name'] . " " . $user['last_name'] ."<br /><br />"; } 

File users.php

 class User{ public static function find_all(){ global $database; $result_set = $database->query("SELECT * FROM `users`"); return $result_set; } public static function find_by_id($id=0){ global $database; $result_set = $database->query("SELECT * FROM `users` WHERE id={$id} LIMIT 1"); $found =$database->fetch_array($result_set); return $found; } } 

I check through var_dump the $ users variable produces (array (1) {[0] => array (5) {[0] => string (1) "1" [1] => string (13) "olegsavchuk12" [2] => string (4) "1111" [3] => string (4) "Oleg" [4] => string (7) "Savchuk"}})

  • one
    And again, "OOP" with global and not the slightest desire to learn. - Ipatiev

1 answer 1

The fact is that you use the fetch_array() method. Try fetch_assoc() . And which database driver do you use?

To use glodal not good, and even bad. In the constructor, you can transfer the database driver. Like that:

 class Users { // Интуитивно понятно, что класс не User, а Users. protected $database; public function __construct(Database $database) { $this->database = $database; } public function find_all() { // Код метода ... используйте $this->database } public function find_by_id($id = 0){ // Точно так же .. } } 

Then create an instance:

 $users = new Users($database); 
  • Thank you very much, the problem was in fetch_array (). I sat for half a day I could not understand what the problem was) - Oleg Savchuk
  • one
    Alas, this answer will not help him. - Ipatiev