Here is my db class for connecting with database using pdo ext.
class db
{
private $host;
private $dbname;
private $username;
private $password;
public function __construct($host,$db,$name,$pass)
{
$this->host=$host;
$this->dbname=$db;
$this->username=$name;
$this->password=$pass;
$dsn = 'mysql:'.$this->dbname.';'.$this->host;
try
{
$conn = new PDO($dsn, $this->username, $this->password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo 'ERROR: ' . $e->getMessage();
}
}
}
I call db class in login class like this...
$host='localhost';
$db='techy_issue_tracker';
$name='root';
$pass='';
$base= new db($host,$db,$name,$pass);
Here is the problem, to make a pdo query inside login class (extending db class) if I use a line this...
$stmnt = $conn->prepare('SELECT id FROM users WHERE name :name OR email = :email');
It generates two errors, saying.. Notice: Undefined variable: conn... and Fatal error: Call to a member function prepare() on a non-object...
I can fix this by simply putting all pdo stuff inside login class but still I am just curious...how do you guys call an object (which is an instance of pdo class?) from another class.
PHP Class Based User System With PDO - Call to a member function prepare() on a non-object This question is interesting but didn't understand much :/
Didn't practice OOP much so some good explanation would be appreciated! Thanks.
You need to intialize
$conn
as a public property of yourdb
class.After the private properties in your
db
class, add this:Then, inside your try catch, change
$conn
to$this->conn
:Then, assuming you've correctly extended the
db
class, you can accessconn
in this manner:$stmt = $db->conn->prepare('SELECT id FROM users WHERE name :name OR email = :email');
There's an error in your WHERE clause:
You're missing an equal sign:
Why don't you just add a method to the db class that takes in a sql string and returns an array of object. Just do all the statement thingy in that method. Then the login class can just call this method to do any query. It does not need to know how the database connection is implemented. This way, if you want to change the underlying implementation in future. It only affects the db class. Not much changes is to be done to the login class as all database accesses goes through the db class.