Search the Community
Showing results for tags 'improvement'.
-
I want to clean up my code by inheriting the database class so I can connect from any class that wants to inherit the database connection. I'm not sure this is the right way but I thought about fixing this by inheriting the __construct function, but how would I call it in this example? Currently I have this; it works, but could this be improved? Or is there a better, cleaner way to do this? $pdo = parent::__construct(); My code: class database { function __construct(){ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "temp"; $pdo = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $pdo; } } class user extends database { public function getAll(){ $pdo = parent::__construct(); $sql = "SELECT name FROM users"; $stmt = $pdo->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); return $result; } } $user = new user; $getAllUsers = $user->getAll(); foreach($getAllUsers as $row){ echo $row['name']; }
- 3 replies
-
- asking for suggestion
- improvement
-
(and 2 more)
Tagged with: