Thursday, 15 September 2011

php - I cant echo the username in OOP -



php - I cant echo the username in OOP -

i cant figure out why maintain getting 2 errors.

notice: undefined variable: username in c:\xampp\htdocs......index.php on line 8

fatal error: cannot access empty property in c:\xampp\htdocs.......index.php on line 8

heres db class <?php class db { private static $_instance = null; private $_pdo, $_query, $_error = false, $_results, $_count = 0; private function __construct() { seek { $this->_pdo = new pdo('mysql:host=' . config::get('mysql/host') . ';dbname=' . config::get('mysql/db'), config::get('mysql/username'), config::get('mysql/password')); }catch(pdoexception $e){ die($e->getmessage()); } } public static function getinstance() { if(!isset(self::$_instance)) { self::$_instance = new db(); } homecoming self::$_instance; } public function query($sql, $params = array()) { $this->_error = false; if($this->_query = $this->_pdo->prepare($sql)) { $x =1; if(count($params)) { foreach($params $param) { $this->_query->bindvalue($x, $param); $x++; } } if($this->_query->execute()){ $this->_results = $this->_query->fetchall(pdo::fetch_obj); $this->_count = $this->_query->rowcount(); }else { $this->_error = true; } } homecoming $this; } public function action($action, $table, $where = array()) { if(count($where)=== 3) { $operators = array('=', '>', '<', '>=', '<=' ); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "{$action} {$table} {$field} {$operator} ?"; if(!$this->query($sql, array($value))->error()) { homecoming $this; } } } homecoming false; } public function get($table, $where) { homecoming $this->action('select *', $table, $where); } public function delete($table, $where) { homecoming $this->action('delete', $table, $where); } public function results(){ homecoming $this->_results; } public function error() { homecoming $this->_error; } public function count() { homecoming $this->_count; }

here index.php

<?php require_once 'core/init.php'; $user = db::getinstance()->get('users', array('username', '=', 'alex')); if(!$user->count()) { echo 'no user'; } else { foreach($user->results() $user) { echo $user->$username, '<br>'; } }

the connection db works, prepare works successfully, bindvalue works successfully, count method works well, if seek user not exist db returns false/'no user', when utilize foreach echo actual username 2 errors , that's stuck. because $user defined getinstance shouldn't define $username , hence not empty property?

you want phone call $user->username not $user->$username.

<?php require_once 'core/init.php'; $user = db::getinstance()->get('users', array('username', '=', 'alex')); if(!$user->count()) { echo 'no user'; } else { foreach($user->results() $user) { echo $user->username, '<br>'; } }

php mysql oop

No comments:

Post a Comment