php - How to convert mysql to mysqli database connection in the constructor -
php - How to convert mysql to mysqli database connection in the constructor -
i trying convert mysql mysqli database connection in constructor.
db.php
<?php define('server', 'localhost'); define('username', 'root'); define('password', 'password'); define('database', 'database'); class db { function __construct(){ $connection = mysqli_connect(server, username, password,database); } } ?> users.php
<?php class users { function __construct(){ $db = new db(); } public function read(){ $query = mysqli_query($db,"select use_id, use_name, use_email users"); while ($row = mysqli_fetch_array($query,mysqli_assoc)){ $data[] = $row; } homecoming $data; } } ?> result.php
<?php require_once('db.php'); ?> <?php require_once('users.php'); ?> <?php $users = new users(); $users = $users->read(); ?> i tried changing mysql mysqli methods, not connecting , read somewhere instantiate db connection in constructor bad idea: please, can explain why, , if there's improve way have db connection available in every class needs it?
a improve practice passing db instance users class. imagine have registration class, login class etc. of constructors create new mysql connection? doesn't thought since of them utilize same database connection.
class users { private $db; public function __construct($db) { $this->db = $db; } .... } $db = new db(); $users = new users($db); php mysql mysqli
Comments
Post a Comment