PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
hello everyone, i am pretty new to this php stuff. i have a connection class which i have created to connect to my database and return an object of the connection. i now want to access that object in another class using it to run a query on my database to fetch items from it. here is the code snipet
<?php
class connection{
public $conn;
public function connect()
{
// create connection object
$conn = new mysqli(SERVER, DB_USER, USER_PWD, DB_NAME);
// test connection
if(mysqli_connect_error()){
throw new Exception("connection failed");
}else{
return conn;
}
}
}
i now want to access the connection object in another class, how do i go about it. this is what i have done.
class testify{
private $db;
public function __construct()
{
// create an object of the database class
$db= new connection();
$db->connect();
}
public function FetchTestimony()
{
$query = "SELECT * FROM test_list";
$result = $this->db->conn->query($query);
if(!$result){
throw new Exception($query);
}else{
return $result;
}
}
}
Last edited by Weirdan on Thu Oct 21, 2010 12:29 pm, edited 1 time in total.
Reason:added syntax highlighting
class testify{
private $db;
public function __construct()
{
// create an object of the database class
$this->db= new connection();
$this->db->connect();
}
public function FetchTestimony()
{
$query = "SELECT * FROM test_list";
$result = $this->db->conn->query($query);
if(!$result){
throw new Exception($query);
}else{
return $result;
}
}
}
<?php
class connection{
public $conn;
public function connect()
{
// create connection object
$conn = new mysqli(SERVER, DB_USER, USER_PWD, DB_NAME);
// test connection
if(mysqli_connect_error()){
throw new Exception("connection failed");
}else{
return conn;
//try this instead
//$this->conn = $conn;
}
}
}