I have a database class which successfully connects to my localhost and to my database, I want to select all the users in my users database however when I am calling my database this is proving to be more difficult that I thought it would be.
I'm getting numerous errors for example:
Notice: Undefined variable: host in E:\xampp\htdocs\attendance\class.Register.php on line 10
Notice: Undefined variable: dbname in E:\xampp\htdocs\attendance\class.Register.php on line 10
Notice: Undefined variable: user in E:\xampp\htdocs\attendance\class.Register.php on line 10
Notice: Undefined variable: pass in E:\xampp\htdocs\attendance\class.Register.php on line 10
Fatal error: Call to undefined method Database::prepare() in E:\xampp\htdocs\attendance\class.Register.php on line 17
However I've defined these in my database class and have told my register class to require the connect file. What am I doing wrong? I can't seem to work out how I should call my database connection in my register class? Anyone have any ideas?
class.Connect.php
<?php // Database connection PDO class Database { public function __construct() { // Connection information $host = 'localhost'; $dbname = 'imanage'; $user = 'root'; $pass = ''; // Attempt DB connection try { $this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //echo 'Successfully connected to the database!'; } catch(PDOException $e) { echo $e->getMessage(); } } public function __destruct() { // Disconnect from DB $this->pdo = null; //echo 'Successfully disconnected from the database!'; } } ?> class.Register.php
<?php require 'class.Connect.php'; class Register { public function __construct() { $this->pdo = new Database($host, $dbname, $user, $pass); //ofcourse you can get the db connections details and database name from a config file } public function viewall() { $sql = "SELECT * FROM users"; $stmt = $this->pdo->prepare($sql); $stmt->execute(); // here you go: $users = $stmt->fetchAll(); foreach ($users as $row) { print $row["firstname"] . "-" . $row["lastname"] ."<br/>"; } } } $run = new Register(); $run->viewall(); ?>