Database class design - php

I'm creating a web app with various classes for things like the user, Smarty template control, etc.
I already have a database class which is all well and good, but I'm concerned about the performance of it.
Currently, in another class, I'm doing $this->db = new DB() to create a local database instance, however the database class's __construct() function creates a new connection to the MySQL server every time I make a new DB() instance, which is obviously less than sensible. This means that each instance of all my different classes that uses the database class makes a connection to the server. I don't have a vast amount of classes, but I only want one per page load.
This is a stripped down sample of what I have at the moment:
// Database class used by multiple other classes
class DB {
private $dbh;
function __construct() {
$this->dbh = // PDO connection here
}
public function query($str) {
// Do a query
}
}
// Example class User
class User {
private $db; // Stores local instance of DB class.
function __construct() {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
I'm looking for the "best" or most common practice of doing this. I don't want to make 10-ish separate connections for each page load.
I want to know what the best way of using and managing a DB class in my application. My four thoughts are these:
Would using a persistent connection to the MySQL server solve this multiple connection issue for me?
Should I use a static factory class and return a DB instance instead of using new DB()?
Is the proper solution to use an entirely static class and just do DB::query() (for example) every time I reference it?
I often use multiple classes in another (so we might have class Folders which requires classes User, DB and Smarty). Is it general practice to extend each class somehow?

If you make the variable holding the connection static, then you can check if you already established a connection. Static variables are the same across all instances of the class, so you can create 100 instances that all use the same connection. You just need to reference it statically: self::$dbh instead of $this->dbh.
class DB {
private static $dbh = null;
function __construct() {
if ( is_null(self::$dbh) ) {
self::$dbh = // PDO connection here
}
}
}

I would suggest you to check the $this -> db at first and then only create it.
function __construct() {
if(!isset($this -> db) || !is_a("DB", $this -> db)) {
$this->db = new DB(); // Makes a new connection in DB::__construct()
}
}

You need to inject db connection to your class instead of creating a new connection.
// In a bootstrap file
$db = new DB();
// User.php
class User {
private $db;
function __construct($db=null) {
if (!is_null($db)) {
$this->setConnection($db);
}
}
function setConnection($db) {
$this->db = $db;
}
public function login() {
$this->db->query('SELECT * FROM users');
}
}
BTW, Zend_Registry is a good solution if you prefer it http://framework.zend.com/manual/en/zend.registry.using.html

<?php
class DBLayer {
public $prefix;
public $link_id;
public $query_result;
public $saved_queries = array();
public $num_queries = 0;
public function DBLayer() {
$db_prefix = '';
$this->prefix = $db_prefix;
if (isset($this->link_id)) {
return $this->link_id;
}
$this->link_id = #mysql_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, true);
if ($this->link_id) {
if (#mysql_select_db(DATABASE_NAME, $this->link_id)) {
return $this->link_id;
} else {
$this->wplog("Unable to select database. Host:". DATABASE_HOST. "Database:" . DATABASE_NAME . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
} else {
$this->wplog("Unable to connect to MySQL server. Host: " . DATABASE_HOST . " Error: " . mysql_error(), 'ERROR', __FILE__, __LINE__);
}
}
public function query($sql, $unbuffered = false) {
if(LOG){echo "<hr>$sql";}
$this->query_result = #mysql_query($sql, $this->link_id);
if ($this->query_result) {
return $this->query_result;
} else {
$msg= $sql . "<br /> Error: (" . mysql_errno() . ") " . mysql_error();
$this->wplog($msg);
}
}
public function result($query_id = 0, $row = 0) {
return ($query_id) ? #mysql_result($query_id, $row) : false;
}
public function fetch_assoc($query_id = 0) {
return ($query_id) ? #mysql_fetch_assoc($query_id) : false;
}
public function fetch_row($query_id = 0) {
return ($query_id) ? #mysql_fetch_row($query_id) : false;
}
public function num_rows($query_id = 0) {
return ($query_id) ? #mysql_num_rows($query_id) : false;
}
public function affected_rows() {
return ($this->link_id) ? #mysql_affected_rows($this->link_id) : false;
}
public function insert_id() {
return ($this->link_id) ? #mysql_insert_id($this->link_id) : false;
}
public function get_num_queries() {
return $this->num_queries;
}
public function get_saved_queries() {
return $this->saved_queries;
}
public function free_result($query_id = false) {
return ($query_id) ? #mysql_free_result($query_id) : false;
}
public function escape($str) {
if (function_exists('mysql_real_escape_string'))
return mysql_real_escape_string($str, $this->link_id);
else
return mysql_escape_string($str);
}
public function get_select($q, $onlyone=false) {
$results = array();
$r = $this->query($q);
if ($onlyone) {
return $this->fetch_assoc($r);
}
while ($l = $this->fetch_assoc($r)) {
$results[] = $l;
}
return $results;
}
public function get_error() {
return mysql_error();
}
public function close() {
if ($this->link_id) {
if ($this->query_result)
#mysql_free_result($this->query_result);
return #mysql_close($this->link_id);
}
else
return false;
}
public function auto_execute($table, $data, $type, $criteria='') {
$result = $this->get_select("desc " . $table);
if ($type == "INSERT")
$start = "insert into " . $table . " set ";
elseif ($type == "UPDATE")
$start = "update " . $table . " set ";
$sql = $start;
foreach ($result as $rst) {
foreach ($data as $key => $value) {
if ($key == $rst['Field'] and $key !== 0) {
if ((#ereg('date', $rst['Type'])) && $value == '') {
$sql = $sql . "`".$key."`" . "=NULL, ";
} elseif ((!#ereg('int', $rst['Type']))) {
$sql = $sql . "`".$key."`" . "='" . $value . "', ";
} else {
if (trim($value) != "") {
$sql = $sql . "`".$key."`" . "=" . $value . ", ";
}
}
}
}
}
if ($sql == $start)
return 0;
else {
$sql = substr($sql, 0, strlen($sql) - 2);
if ($type == "UPDATE" and !empty($criteria))
$sql = $sql . " where " . $criteria;
}
//echo $sql;exit;
if ($this->query($sql)) {
$return = $this->insert_id();
} else {
$return = 0;
}
return $return;
}
private function wplog($message) {
if(LOG==true){
$lineBreak = "\n"; // this function will NOT work on a windows server without further modification
$contents = date('Y-m-d H:i:s') . ' ' . $message. $lineBreak;
$myFile = SERVER_PATH.'/log.txt';
$fh = fopen($myFile, 'a') ;
fwrite($fh, $contents);
fclose($fh);
//SetFileContents(SERVER_PATH.'/log.txt',$contents,'a');
}
}
}

Related

i have sql custom execution method, but there are found error unbuffered query

i have a class which has custom query execution. Then it shown some error if after i execute that.
SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.
I have search out my problem answer but, almost of them recommend me to put $stmt->closeCursor() in my code, but i have done with it and still get error. The error shown is same with error above. Below is my DBClassification class. Please help me. Thanks :)
<?php
class DBClassification
{
public $db = null;
public $host = "localhost";
public $user = "root";
private $pass = "";
public $path = __DIR__ . "\\";
public $prefixFilename = "klasifikasi_";
public $dbexception = [];
public $stmt;
public function setHost($host){
$this->host = $host;
}
public function setUser($user){
$this->user = $user;
}
public function setPass($pass){
$this->pass = $pass;
}
public function setPath($path)
{
if (!is_dir($path)) die ("Directory \$path is not correct!\n$path");
$lastchar = substr($path, -1);
if ($lastchar != "/" && $lastchar != "\\") $path = $path . "/";
if (strpos($path, '/') !== false) $path = str_replace("/","\\",$path);
$this->path = $path . $this->host . "\\"; // setting path to the generated output file
}
public function setPrefixFilename($prefixFilename){
$this->prefixFilename = $prefixFilename;
}
public function setDBException($dbexception=[]){
$this->dbexception = $dbexception;
}
public function init($host,$user,$pass,$path,$prefixFilename,$dbexception=[])
{
if (!$dbexception) $dbexception = ["information_schema","mysql","performance_schema","phpmyadmin","sys"];
$this->setHost($host);
$this->setUser($user);
$this->setPass($pass);
$this->setPath($path);
$this->setPrefixFilename($prefixFilename);
$this->setDBException($dbexception);
$this->openConnection();
}
// Establishing Connection to mysql database on specified host
public function openConnection(){
try {
$db = new PDO("mysql:host=".$this->host, $this->user, $this->pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->db = $db;
return true;
} catch (PDOException $e) {
die("Error!: " . $e->getMessage());
}
return false;
}
public function run(){
try {
$databases = $this->stmtExec("SHOW DATABASES",true);
foreach($databases as $database): // execute each database
$dbname = $database['Database']; // database name
if(!in_array($dbname,$this->dbexception)): // prevent clasifying dbname which contain in dbexception
echo "USE $dbname\n";
$this->stmtExec("USE $dbname");
$tables = $this->stmtExec("SHOW TABLES",true);
endif; // if(!in_array($dbname,$dbexception)):
endforeach; // foreach($databases as $database):
} catch (Exception $e) {
echo "Something wrong, failed to clasify each database in host " . $this->host . "\n";
die("Error!: ".$e->getMessage());
}
}
public function stmtExec($sql,$fetch=false)
{
try {
$this->stmt = $this->db->prepare($sql);
if ($fetch) {
if ($this->stmt->execute()) $return = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
$return = $this->stmt->execute();
}
$this->stmt->closeCursor();
} catch (PDOException $e) {
$errormsg = "db Error: ". $this->stmt->queryString . PHP_EOL . $e->getMessage();
$queryFilename = $this->path . "error.txt";
file_put_contents($queryFilename, $errormsg);
print_r($errormsg);die();
}
return $return;
}
}
[ANSWERED]
I have found the solution from that, i have to delete false status in pdo attribute "PDO::ATTR_EMULATE_PREPARES". I think it become error because it will check query in prepare method. And query "use $dbname" is one which has no output and will give error if prepare check is on. Thats all my opinion.

Fixing max_user_connections in PHP class using PDO

I have been adapting an older abstraction layer to use PDO but I am running into user x has more than 'max_user_connections' active connections SQLSTATE[HY000] [1203] errors when looping through large sets. I have been reading on http://php.net/manual/en/pdo.connections.php but all of my attempts to unset the $dbh from within the loops result in errors from having ended the connection.
Base class looks like
class DB {
public $pdo;
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
public function __construct()
{
$this->connect();
}
private function connect()
{
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
try {
$this->pdo = new PDO("mysql:host=$this->host;dbname=$this->dbname;charset=utf8;", $this->user, $this->pass, $options);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function __sleep()
{
return array('dsn', 'username', 'password');
}
public function __wakeup()
{
$this->connect();
}
public function __destruct()
{
$this->connection = null;
$this->pdo = null;
unset($this->pdo);
}
// CRUD methods follow including
function retrieve($where, $groupBy='', $order_by='') {
$query = "SELECT * FROM `$this->table` $where $groupBy $order_by";
$q = $this->pdo->prepare($query);
$q->execute();
$result = $q->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE,get_class($this));
// was $result = $q->fetchAll(PDO::FETCH_CLASS,get_class($this));
$this->query_log($query);
$q = null;
if ($result == 'NULL') {
return false;
} else {
return $result;
}
} // retrieve()
And an example that has the errors would be
if (in_array($_GET['type'], $types)) {
$type = $_GET['type'];
$rsObj = new ReservedSlug;
if ($type == 'artist') {
$obj = new CalendarArtist;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'event') {
$obj = new CalendarEvent;
$slugfield = 'urlSlug';
$namefield = 'name';
} else if ($type == 'location') {
$obj = new Location;
$slugfield = 'UrlSlug';
$namefield = 'LocationName1';
}
$needslug = $obj->retrieve("TRIM(`$namefield`) != '' AND (`$slugfield` = '' OR `$slugfield` IS NULL) LIMIT 0,400");
if ($needslug) {
foreach ($needslug as $ns) {
$testslug = slugify($ns->$namefield);
list($reserved) = $rsObj->retrieve("`slug` = '$testslug' AND `type` = '$type'");
if (!$reserved) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug'");
if ($test) {
for ($i = 2; $i < 26; $i++) {
list($test) = $obj->retrieve("`$slugfield` = '$testslug-$i'");
if (!$test) {
$slug = $testslug . '-' . $i;
}
}
} else { // not found in table
$slug = $testslug;
}
} else { // was reserved
$slug = false;
}
echo $ns->$namefield . " gets $slug<p>";
} // foreach needslug
} // if needslug
} // type found in array
So I need to understand how to not create new connections when an active connection is available and how to properly __destruct() these child objects. Where am I going wrong?

I'm using Unit Of Work Design Pattern with PHP for my project

I'm working on a project which is using Unit of work design pattern. It includes Storage,EntityCollection,..... Code of unit of work includes PDO Adapter code file. But the adapter is not complete for running queries. I have found the files from somewhere.
I can't build queries what I want. Every time I'm writing code I faces to many problems related query. So can you please help me to make it more flexible... For example i want to run like : $db->select()->where('id>:id')->andWhere('')->orWHere()->orderBy()->groupBy()->having()->fetch()/fetchOne(); or similar to it.
<?php
namespace D\Adapter;
class PdoAdapter implements \D\DB\DatabaseInterface {
protected $config = array();
protected $database;
protected $connection;
protected $statement;
protected $fetchMode = \PDO::FETCH_ASSOC;
public function __construct($dsn, $username = null, $password = null, array $driverOptions = array()) {
$this->config = compact("dsn", "username", "password", "driverOptions");
$this->database = $driverOptions['db_name'];
}
public function getStatement() {
if ($this->statement === null) {
throw new \PDOException(
"There is no PDOStatement object for use.");
}
return $this->statement;
}
public function connect() {
// if there is a PDO object already, return early
if ($this->connection) {
return;
}
try {
$this->connection = new \PDO(
$this->config["dsn"], $this->config["username"], $this->config["password"], $this->config["driverOptions"]);
$this->connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->connection->setAttribute(
\PDO::ATTR_EMULATE_PREPARES, false);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function disconnect() {
$this->connection = null;
}
public function prepare($sql, array $options = array()) {
$this->connect();
try {
$this->statement = $this->connection->prepare($sql, $options);
return $this;
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function execute(array $parameters = array()) {
try {
$this->getStatement()->execute($parameters);
return $this;
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function countAffectedRows() {
try {
return $this->getStatement()->rowCount();
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
/**
* countAffectedRows iin Alias
*/
public function count() {
try {
return $this->getStatement()->rowCount();
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function getLastInsertId($name = null) {
$this->connect();
return $this->connection->lastInsertId($name);
}
public function fetch($fetchStyle = null, $cursorOrientation = null, $cursorOffset = null) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $this->getStatement()->fetch($fetchStyle, $cursorOrientation, $cursorOffset);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function fetchAll($fetchStyle = null, $column = 0) {
if ($fetchStyle === null) {
$fetchStyle = $this->fetchMode;
}
try {
return $fetchStyle === \PDO::FETCH_COLUMN ? $this->getStatement()->fetchAll($fetchStyle, $column) : $this->getStatement()->fetchAll($fetchStyle);
} catch (\PDOException $e) {
throw new \RunTimeException($e->getMessage());
}
}
public function select($table, $bind = array(), $where = "", $options = array()) {
if (count($bind) > 0) {
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
}
if (isset($options['fields'])) {
$fields = $options['fields'];
} else {
$fields = '*';
}
$sql = "SELECT " . $fields . " FROM " . $table . " ";
if (strlen($where) > 2) {
$sql .= "WHERE " . $where;
}
// set_flash($sql);
$this->prepare($sql)
->execute($bind);
return $this;
}
public function query($sql, array $bind = array()) {
if (is_array($bind)) {
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
}
$this->prepare($sql)
->execute($bind);
return $this;
}
public function insert($table, array $bind) {
$cols = implode(", ", array_keys($bind));
$values = implode(", :", array_keys($bind));
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
}
$sql = "INSERT INTO " . $table
. " (" . $cols . ") VALUES (:" . $values . ")";
return (int) $this->prepare($sql)
->execute($bind)
->getLastInsertId();
}
public function update($table, array $bind, $where = "") {
$set = array();
foreach ($bind as $col => $value) {
unset($bind[$col]);
$bind[":" . $col] = $value;
$set[] = $col . " = :" . $col;
}
$sql = "UPDATE " . $table . " SET " . implode(", ", $set)
. (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute($bind)
->countAffectedRows();
}
public function delete($table, $where = "") {
$sql = "DELETE FROM " . $table . (($where) ? " WHERE " . $where : " ");
return $this->prepare($sql)
->execute()
->countAffectedRows();
}
public function fetchAllTables() {
$sql = "SHOW TABLES FROM " . $this->database;
$this->prepare($sql)
->execute();
return $this;
}
public function fetchAllFields($table) {
$sql = "SHOW FIELDS FROM " . $table;
$this->prepare($sql)
->execute();
return $this;
}
}
---FULL code is here---
https://github.com/batmunkhcom/mbm/tree/master/src/D
First of all the concern of an UnitOfWork Pattern is to track everything you do during a business transaction that can affect the database. After transactions, it figures out everything that needs to be done to alter the database as a result of your work. Your class has other concerns.
It looks like a godclass (antipattern). It has more than one responsibility: Connection, PeparedStatement, Execution, and other helpers. Its quite difficult to scale and maintain. Try to split all responsibilities to different classes in SOLID way with corresponding design pattern.
Your idea faced in your code is already done by other frameworks. Its very hard work to implement it again. For example you can try Doctrine ORM/DBAL Framework.

store multiple pdo connections in an array

so i have been trying to debug this issue myself for a few days now and i can't seem to figure out why i'm not getting the results I expect.
My code is rather complex and for a DB connection to be establish it spans across 3 Classes and one config file.
but basically my end usage ends up being
$this->db('test')->query('SELECT * FROM test1');
this establishes a connection to my database by the alias of test the query returns results so i'm good so far.
now my issue is when i try to make a new PDO object.
$this->db('test2')->query('SELECT * FROM test2');
this returns nothing because there is not table called test2 in my test1 object.
but if I do this
$this->db('test2')->query('SELECT * FROM test1');
now this returns the same results from the first PDO object.
I have traced and tracked down every line of code to make sure that the correct parameters are being passed to my database class and that each connection is properly established to the corresponding databases.
now my question is, can you have more than one datbase pdo connection? if so is there a special flag that needs to be set in the PDO options? are my connections being cached somewhere and causing this confusion?
this is my PDO declaration in each new class object stored in my array of connections
try
{
$this->_con = new PDO(
"mysql:host=" . $host . ";
port=" . $port . ";
dbname=" . $name, $user, $pass
);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// TODO: push all $e methods to the developer debugger
echo "Database Error: ". $e->getMessage();
}
edit my code that uses the connection
step 1: a call to the parent class
public function __call($name, $params)
{
$class = $name . '_system_helper';
$hash = md5($class . $params);
if (class_exists($class))
{
if (!array_key_exists($hash, $this->_sys_helper))
{
if (method_exists($class, 'init'))
{
$this->_sys_helper[$hash] = call_user_func_array(array($class, 'init'), $params);
} else {
$this->_sys_helper[$hash] = call_user_func_array($class, $params);
}
}
return $this->_sys_helper[$hash];
}
return null;
}
step 2: called from the parent class
class DB_System_Helper extends Jinxup
{
private $_con = null;
public function __construct($end = null)
{
$mode = null;
$host = null;
$name = null;
$user = null;
$pass = null;
$port = null;
if (isset($this->config['database']['mode']))
{
$mode = $this->config['database']['mode'] == 'production' ? 'production' : 'development';
if (count($this->config['database'][$mode]) > 1)
{
foreach ($this->config['database'][$mode] as $key => $database)
{
if ($database['#attr']['alias'] == $end)
{
$host = $this->config['database'][$mode][$key]['host'];
$name = $this->config['database'][$mode][$key]['name'];
$user = $this->config['database'][$mode][$key]['user'];
$pass = $this->config['database'][$mode][$key]['pass'];
$port = $this->config['database'][$mode][$key]['port'];
}
}
} else {
$host = $this->config['database'][$mode]['host'];
$name = $this->config['database'][$mode]['name'];
$user = $this->config['database'][$mode]['user'];
$pass = $this->config['database'][$mode]['pass'];
$port = $this->config['database'][$mode]['port'];
}
$this->_con = new PDO_Database_Helper($host, $name, $user, $pass, $port);
} else {
echo 'No database mode specified';
}
}
public function __call($name, $param)
{
return call_user_func_array(array($this->_con, $name), $param);
}
}
step 3: called from DB_System_Helper
class PDO_Database_Helper extends Jinxup
{
private $_con = null;
private $_id = 0;
public function __construct($host, $name, $user, $pass, $port = 3306)
{
try
{
$this->_con = new PDO(
"mysql:host=" . $host . ";
port=" . $port . ";
dbname=" . $name, $user, $pass
);
$this->_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
// TODO: push all $e methods to the developer debugger
echo "Database Error: ". $e->getMessage();
}
}
[...]
}
Are you sure that the hashing you're doing is enough to "namespace" each connection in the $this->_sys_helper array?
I suspect the problem lies in the first stage.
public function __call($name, $params)
{
$class = $name . '_system_helper';
$hash = md5($class . $params);
if (class_exists($class))
{
if (!array_key_exists($hash, $this->_sys_helper))
{
if (method_exists($class, 'init'))
{
$this->_sys_helper[$hash] = call_user_func_array(array($class, 'init'), $params);
} else {
$this->_sys_helper[$hash] = call_user_func_array($class, $params);
}
}
>>>>>>>>>>>>>> are you sure this is not returning the wrong
>>>>>>>>>>>>>> connection because of how the hashing is working?
return $this->_sys_helper[$hash];
}
return null;
}

Require Once stops script

I have a php script, test.php that has the contents
<?php
require_once("classes/user.php");
echo "test";
?>
and here is the contents of user.php
<?php
class User {
private $data = array();
public function __set($name, $value) {
$this->data[$name] = $value;
}
public function __get($name) {
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
public function __isset($name) {
return isset($this->data[$name]);
}
public function __unset($name) {
unset($this->data[$name]);
}
public __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
private id($id) { //select from database
require_once('config.php');
$pdo = new PDOConfig();
$sql = "SELECT * FROM users WHERE `id` = :id";
$q = $pdo->prepare($sql);
$q->execute(array(":id"=>$id));
$resp = $q->fetchAll();
foreach ($resp as $row) {
foreach ($row as $key=>$value) {
if(!is_int($key))
$this->data[$key] = html_entity_decode($value, ENT_QUOTES);
}
}
$pdo = null;
unset($pdo);
}
private create($arr) { //create new item from values in array and insert to db
}
public delete() {
$this->life = 0;
//update database "life" here
}
/* ##################################### */
/* !Functions */
/* ##################################### */
public projects($extra = null) {
$projects = array();
require_once('project.php');
$pdo = new PDOConfig();
$sql = "SELECT * FROM ---- WHERE `000` = :aaa";
if($extra) $sql .= " " . $extra;
$q = $pdo->prepare($sql);
$q->execute(array(":aaa"=>$this->id));
$resp = $q->fetchAll();
foreach ($resp as $row) {
$project = new Project($row['id']);
$projects[] = $project;
$project = null;
unset($project);
}
return $projects;
}
}
?>
and test is never printed, and on chrome the page doesn't load at all
The website encountered an error while retrieving http://example.com/test.php. It may be down for maintenance or configured incorrectly.
I can't figure this out for the life of me. Thanks it advance
You have a syntax error in the declaration of your __construct() method :
public __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
You need to use the function keyword, like this :
public function __construct($param) {
if(is_array($param)) $this->create($param);
else $this->id($param);
}
To help find those errors, on your development computer, you should enable :
error_reporting
and display_errors
In fact, I just copy-pasted your code to a .php file and ran it -- and got a nice
Parse error: syntax error, unexpected T_STRING, expecting T_VARIABLE
in /home/.../temp/temp.php on line 39

Categories