Reputation: 113
I created connection class that returns pdo connection object. Other model classes extend that class. In view mode, I try to get output using namespace and autoload class, but it occur some fatal error 'call to a member function query() on a non-object' . Help me to solve this.
This is Connection.php
namespace myproject;
use PDO;
class Connection
{
private $host = "localhost";
private $user = "root";
private $pass = "";
private $dbname = "mydb";
public $dbh;
private $error;
public function __construct()
{
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->dbh;
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
}
}
}
Then I extend this class to other class Form.php
namespace myproject;
use myproject\Connection;
class Form extends Connection
{
public function GetUser($id)
{
$sql = "select * from users where uid='$id'";
$query = $this->dbh->query($sql);
$data = $query->fetch(PDO::FETCH_ASSOC);
$uname = $data[first_name]." ".$data[last_name];
return $uname;
}
}
In front-end page, it came error message I pointed out above.
namespace myproject;
include 'Form.php';
include 'Connection.php';
$test = new Form();
echo $test->GetUser(1);
Upvotes: 0
Views: 442
Reputation: 6539
Your Form.php file should be:-
namespace myproject;
use PDO; // add this line
class Form extends Connection{
public function GetUser($id)
{
$sql = "select * from users where uid='$id'";
$query = $this->dbh->query($sql);
$data = $query->fetch(PDO::FETCH_ASSOC);
// added single quotes around first_name and last_name
$uname = $data['first_name']." ".$data['last_name']; // added single quotes around first_name and last_name
return $uname;
}
}
Your View file should be:-
<?php
namespace myproject;
include 'Connection.php'; // include connection file first
include 'Form.php'; // include form file second
$test = new Form();
echo $test->GetUser(1);
Hope it will help you :-)
Upvotes: 1