im verry new to classes and PDO. I've searched for hours and hours on google to find a solution for probably an easy problem.
The thing is. I have made a class to connect to my database. Then, i made a class to load information from a database using queries. Then, i use a script to combine both classes. Though, even if i connected to the database, it still has trouble understanding it in my other class. I keep getting the errors:
Undefined variable: db
Trying to get property of non-object in
Call to a member function prepare() on a non-object in
all regarding to my $query = $db->conn->prepare statement in the Invoice class.
How can i solve this??
I have the following database class:
class database
{
private $host;
private $dbname;
private $username;
private $password;
public $conn;
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 {
$this->conn = new PDO($dsn, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo"connection made";
} catch (PDOException $e) {
echo"Could not connect to the database";
die;
}
}
}
?>
then, there is the class that builds information from a database (invoice class)
class Invoice{
var $customerID;
var $customerSalutation;
var $customerFirstName;
var $customerMiddleName;
var $customerLastName;
var $customerCompanyName;
var $customerStreetName;
var $customerHouseNumber;
var $customerHouseNumberSuffix;
var $customerPostalCode;
var $customerCountry;
function set_customer($id){
if ((!isset($id)) or ($id=="")){
echo "No customerID specified";
die;
} else {
if (ctype_digit($id)){
$query = $db->conn->prepare('
SELECT CustomerID, CustomerSalutation, CustomerFirstName, CustomerMiddleName, CustomerLastName, CustomerCompanyName, CustomerStreetName,
CustomerHouseNumber, CustomerHouseNumberSuffix, CustomerPostalCode, CustomerCountry WHERE CustomerID = :customerID');
$array = array (
'customerid' => $this->customerID
);
$query->execute($array);
} else {
echo "Invalid customer ID";
die;
}
}
}
}
?>
I all open it, in the following basic script:
<?php
include('database.php'); //open database class
$host="localhost";
$db="dbname";
$name="root";
$pass="";
$db = new database($host,$db,$name,$pass);
include('InvoiceBuilderClass.php'); //include invoice class
$invoice = new Invoice();
$cusID="1";
$invoice->set_customer($cusID);
?>