I am trying to display items in cart.I created two classes cart.php,database.php.both are in different directories.When i execute cart.php page i get the error.
Notice: Undefined variable: db in C:\ runk\library\classes\cart.php on line 12
Fatal error: Call to a member function find_by_id() on a non-object in C:\ runk\library\classes\cart.php on line 12
cart.php code
require_once('c:\ runk\\library\\configuration\\paths.php');
var_dump($db);
class Cart
{
var $items=0;
var $price=0;
public function add_item($p_id)
{
$query='SELECT product_name,product_price FROM products WHERE product_id='.$p_id;
$item=$db->find_by_id($query);
echo $item->product_name;
}
}
$shopping_cart=new Cart();
$p_id=$_GET['p_id'];
switch ($_GET['action'])
{
case 'add_item':
$shopping_cart->add_item($p_id);
}
Database.php code
class Database
{
public $connection;
public function open_connection()
{
$this->connection=mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if(!$this->connection)
{
die("Database Connection Failed".mysql_error());
}
else
{
$db_select=mysql_select_db(DB_NAME,$this->connection);
if(!$db_select)
{
die("Database not found".mysql_error());
}
}
}
public function find_by_id($query)
{
$result_set=mysql_query($query,$this->connection);
$result_set=$this->fetch_assoc($result_set);
$result=(object)$result_set;
return $result;
}
public function fetch_assoc($result_set)
{
return mysql_fetch_assoc($result_set);
}
}
$db=new Database();
$db->open_connection();
I can able to access the $db object in the previous page of cart.php.How to solve it?