Hello everybody,
problem making a connection to a class.connection.php from class.list.php to query the database
I have 3 files:
index.php: which displays the results returned from class.list.php
class.list.php: pulls in a list of names and returns the results to index.php to display in a html table.
connection.php: has the database connection information
now, it works if in include the database connection in the list.php class but I like to keep it septate so that i dont have to repeat the connection code.
any help you can provide would be greatly appreciated.
Index.php - to make it simple i shortened the code. this is just to display on the screen
</tr>
<?php
include('connection.php');
include('class.list.php');
$projectID = 'PROJECTK6YGTR';
$newList = new list($projectID);
foreach($newList->listdisplay() as $row)
{ echo '<tr>';
echo '<td>'. $row['firstname'] . '</td>';
echo '<td>'. $row['lastname'] . '</td>';
echo '</tr>';
}
?>
</table>
class that queries the information from the database and returns it to index.php for display
class list
{ private $ListArray;
private $projectId;
public function __construct($prjID)
{ $this ->projectId = $prjID;
$this->dbConnection();
} // end of construct
public function dbConnection()
{ try { $stmt = $db->query("SELECT * from tbl_user ");
$this->ListArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{ echo $e->getMessage(); }
}
public function listdisplay()
{ return $this->ListArray; }
} // end of class
connection.php - script i picked up on the internet
<?php
class Connection
{
public static $db = false;
private $database_host = 'localhost';
private $database_user = 'testuser';
private $database_pass = 'testpwd';
private $database_db = 'testdb';
function __construct()
{
if (self::$db === false) {
$this->connect();
}
}
private function connect()
{
$dsn = $this->database_type . ":dbname=" . $this->database_db . ";host=" .
$this->database_host;
try {
self::$db = new PDO($dsn, $this->database_user, $this->database_pass,
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \\'UTF8\\''));
self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
//your log handler
}
}
}
?>