How to connect to the database in OOP?

0 like 0 dislike
5 views
Good afternoon. Write a class for connecting to database and further withdrawal information.
<?phpclass DB{protected $connection;public function __construct($host, $user, $password, $db_name) {$this->connection = new mysqli($host, $user, $password, $db_name); if( !$this->connection ) { throw new Exception('error'); } } public function getAllInformationFromTableUsers() { $getAllInformationFromTableUsers = $this->connection->query("SELECT * FROM tableUs"); $row = $getAllInformationFromTableUsers->fetch_assoc(); $this->connection->close(); return $row["id"]; } }

Tell me where and how to declare variables $host, $user, $password, $db_name. The fact is that when you declare them as follows:
<?phpclass DB{public $host = "localhost";public $user = "example";public $password = "12345678";public $db_name = "exampledb";protected $connection;public function __construct($host, $user, $password, $db_name) {$this->connection = new mysqli($host, $user, $password, $db_name); if( !$this->connection ) { throw new Exception('error'); } } }

I get an error Missing argument 1 for DB::__construct()
Not an expert in OOP, but would like to learn this style of writing code.
by | 5 views

3 Answers

0 like 0 dislike
Write a class for connecting to database and further withdrawal information.

This is great, but would like to suggest to start to learn OOP syntax, as it should be at least a basic understanding, and then write a simple class to understand what is object, how to call its methods, how to work with multiple objects, how and why to divide the scope of methods and properties, and only then to write something more complex (the DB connection)

I get an error Missing argument 1 for DB::__construct()

Accessing the properties of the current object, is as follows:
$this->host // access $host
$this->user // reference to $user
...

i.e. in your example code, you can do so
public function __construct() { $this->connection = new mysqli($this->host, $this->user, $this->password, $this->db_name); if( !$this->connection ) { throw new Exception('error'); } }


well, of course that the configs for the DB connection to make public.. say no need.
Scope of properties (variables)
by
0 like 0 dislike
give default values to connect.
by
0 like 0 dislike
The mistake is that you have a constructor with parameters and you inicializirati an object of class DB with no parameters.
by

Related questions

0 like 0 dislike
1 answer
asked Jun 7, 2019 by narem
0 like 0 dislike
2 answers
asked Aug 1, 2019 by Flappy1488
0 like 0 dislike
6 answers
0 like 0 dislike
5 answers
0 like 0 dislike
2 answers
110,608 questions
257,186 answers
0 comments
33,570 users