Static method calling result of mysql query - php

I have
class Check
{
public function __construct()
{
$this->db = new Database();
}
public function query()
{
$login = Session::get("login");
$sth = $this->db->prepare('SELECT admin FROM accounts WHERE login=:login');
$sth->execute(array(':login' => $login));
$result = $sth->fetch(PDO::FETCH_NUM);
return $result[0];
}
public static function admin()
{
echo self::query();
}
}
I have Database class in another place with PDO connection.
class Database extends PDO
{
public function __construct()
{
parent::__construct('mysql:host=localhost;dbname=name','root','pass');
$this->query('SET NAMES utf8');
}
}
So after Check::admin() code I get error:
Undefined property: View::$db
Why?

You are using a static method, that wants to use a instance variable.
Your admin method calls the query method, and the query method is using the db instance variable. As your class is not instantiated, the db variable does not exists.
My suggestion would be to make the admin method non static and use your code like this:
$mycheck = new Check();
$mycheck->admin();
or, if you are on php 5.4 and want to stick with a oneliner:
(new Check())->admin();
update
note: Do not create the db class in the constructor, but inject it:
public function __construct(Database $db)
{
$this->db = $db;
}

Sorry this is not direct answer for your question but your code has some issues so take some time and examine this and ask if it's not clear for you.
<?php
class Check {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
public function query(ISession $sessionData) {
//WHY IS THE SESSION STATIC?
//$login = Session::get("login");
$sth = $this->_db->Connection()->prepare('SELECT admin FROM accounts WHERE login=:login');
$sth->execute(array(':login' => $sessionData->get("login")));
$result = $sth->fetch(PDO::FETCH_NUM);
return $result[0];
}
public function admin(ISession $sessionData) {
// REALLY BAD TO ECHO HERE
echo $this->query($sessionData);
}
}
class Database {
private $_name;
private $_password;
private $_connStr;
private $_settings;
private $_pdo;
public function __construct($connstr, $name, $password, array $settings = array()) {
$this->_name = $name;
$this->_password = $password;
$this->_connStr = $connstr;
$this->_settings = $settings;
}
public function Connection() {
if ($this->_pdo == NULL) {
$this->_pdo = new PDO($this->_connStr, $this->_name, $this->_password);
}
return $this->_pdo;
}
/* other fancy methods */
public function Close() {
$this->_pdo = NULL;
}
public function __destruct() {
$this->Close();
}
}
And i don't see why you need a Check class for all this becouse if i were you i would create somethinf like this:
$currentSession = Session::GetCurrent();
$currentSession->User()->IsInRole('admin');
Note that the session is not static and if i would write a more complete solution i would avoid Session::GetCurrent() call becouse the current session would be a field in some class' instance (HttpApplication for example).

Related

Assign a public static function's return value to a private variable

There are two classes:
class Db {
public static function getConnection () {
/*Initialize parameters*/
$db = new PDO (...);
return $db;
}
}
Class Db initializes and returns a PDO object.
Then I want to do following in another class:
class User {
private $db = Db::getConnection();
....
}
Why am I getting an error here:
private $db = Db::getConnection();
Without knowing the error, it's hard to say, but I'd guess is because you can't do that there, try this.
class User {
private $db = null;
function __construct(){
$this->db = Db::getConnection();
}
public function getFriends(){
return $this->db->query('SELECT * FROM friends');
}
}

PHPUnit_Extensions_Database_Testcase returns undefined method

Im getting a Fatal error: Call to undefined method PHPUnit_Extensions_Database_DB_DefaultDatabaseConnection::prepare() on a phpunit test where I'm preparing a PDO statement. If the default database connection is a copy of the pdo object that successfully connects, wouldn't it have access to its methods?
My Class and the function in question:
class User
{
protected $db;
public function __construct($db)
{
$this->db = $db;
}
public function deleteItem($itemId)
{
$sql = "
DELETE FROM Users WHERE id = ?";
$sth = $this->db->prepare($sql);//this is the failed line works on other tests
return $sth->execute(array($itemId));
}
My Test:
class RosterDBTest extends PHPUnit_Extensions_Database_Testcase
{
public function getConnection()
{
$pdo = new PDO('mysql:host=localhost;dbname=users','root','root');
return $this->createDefaultDBConnection($pdo,"users");
}
public function getDataSet()
{
return $this->createFlatXMLDataset(
dirname(__FILE__) . '/users.xml');
}
public function setup()
{
$this->db = $this->getConnection();
}
public function testRemoveUser()
{
$testUser = new User($this->db);
$expectedUsers = 123;
$testUser->deleteItem(91);
$totalUsers = $testUsers->getAllUsers();
$this->assertEquals( $expectedUsers,count($totalUsers), 'Did not delete User 91' );
}
I've just been stuck on a similar problem where I had my abstract database testcase class. Solved it by changing
public function setup()
{
$this->db = $this->getConnection();
}
to
public function setup()
{
$this->db = $this->getConnection()->getConnection();
}
Not sure if this helps with this but hopefully will help someone.

Share a parameters class with other classes

I would like to share the parameters taken from a table in a db.
To take these parameters, I created a class made ​​for this.
this is my scenario to share the parameters contained in a db between the various classes. is the correct approach to do this?
class Database
{
$private mys;
public function __construct()
{
$this->mys = new mysqli(....);
}
}
class params
{
$private db;
$public var1;
$public var2;
public function __construct()
{
$this->db = new Database();
}
public function getParams()
{
$result = $this->db->mys->query ("SELECT * FROM params");
while($row = $result->fetch_assoc())
{
$this->var1 = $row['var1'];
$this->var2 = $row['var2'];
}
}
}
class foo
{
private $db;
private $ps;
public function __construct()
{
$this->db = new Database;
$this->ps = new Params;
}
public function viewParams()
{
echo $this->ps->var1;
echo $this->ps->var2;
}
}
To access the private fields from other classes declare public 'getter' methods like:
public getVal1() {
return $this->val1;
}
In my modest opinion, there are various ways to share a parameters class with other classes. And they depends on how your system currently is and how it'll grow.
From what I learnt, a correct ways to pass dependencies to your classes is to inject they to the constructor, ex instead of:
class foo
{
...
public function __construct()
{
$this->db = new Database;
I would prefer to instanciate $db first:
$db = new Database();
and then
class foo
{
...
public function __construct(Database $db)
{
$this->db = $db;
This way your classes are loosely coupled and you can afford Unit Testing easily one day, working with interfaces and not concrete implementations, etc...please take a look at http://en.wikipedia.org/wiki/Dependency_injection
As a personal suggest I'll try to design the params class as an entity, mapped as a Db table object:
//entityParams.php
class EntityParams
{
private $id; //column name
private $columnA;
private $columnB;
public function setId($id)
{
$this->id = $id;
}
public function setColumnA($columnA)
{
$this->columnA = $columnA;
}
...
}
then use a Database class as a simple connector class (just to promotes single-responsibility and separation of concerns):
//Database.php
class Database
{
private $dbh = NULL;
public function connect()
{
$this->dbh = new Mysqli(...);
}
public function getConnection()
{
if(is_null($this->dbh))
{
$this->connect();
}
return $this->dbh;
}
}
and use a DatabaseManager instead, to let it do all dirty works.Something like:
//DatabaseManager.php
class DatabaseManager
{
private $db;
private $entities = array();
private $currentEntity;
public function __construct(Database $db)
{
$this->db = $db;
}
public function fromEntity($entityName)
{
$entityClass = "Entity".ucfirst($entityName);
if(!isset($this->entities[$entityClass]))
{
$this->entities[$entityClass] = $entityName;
}
$this->currentEntity = $entityClass;
return $this;
}
public function getAll()
{
$results = $this->db->getConnection()->query("SELECT * FROM {$this->entities[$this->currentEntity]}");
$entities = array();
foreach ($results->fetch_all(MYSQLI_ASSOC) as $key => $item)
{
$e = new $this->currentEntity;
$e->setId($item['id']);
$e->setColumnA($item['columnA']);
$e->setColumnB($item['columnB']);
$entities[] = $e;
}
return $entities;
}
Finally your Foo class (and everyone else) just has a simple dependency with the DatabaseManager (which could evolve as a RespositoryManager):
//Foo.php
class Foo
{
public $dbm;
public function __construct(DatabaseManager $dbm)
{
$this->dbm = $dbm;
}
public function viewParams()
{
return $this->dbm->fromEntity("params")->getAll();
}
public function viewParam($id)
{
return $this->dbm->fromEntity("params")->find(2);
}
}
//client.php
/* Here you can instantiate the classes and pass they through constructor or investigate on how to create and use a Dependency Injection Container */
$db = new Database();
$dbm = new DatabaseManager($db);
$foo = new Foo($dbm);
var_dump($foo->viewParams());
var_dump($foo->viewParam(1));
I just wrote simple basic ideas that could be worth to play around it and improve it.

How to use $db instead of $GLOBALS['db'] in my classes?

I need to use $GLOBALS['db'] in my classes ($db is defined in my index.php), but I don't want to use $GLOBALS['db'] when I have to call it.
I wrote this code at the beginning of my classes :
class ClassName
{
var $db;
public function __construct()
{
$this->db = $GLOBALS['db'];
}
public function test()
{
$val = $this->db->oneValue('SELECT first_name FROM users LIMIT 0, 1');
echo $val->first_name;
}
}
But I'm not enjoying this; I prefer to use directly $db in my code. Is there a solution to be able to call $GLOBALS['db'] by $db?
Simples, just inject in the constructor or a setter method: (I'm assuming $db is an object here, not an array of connection parameters etc)
class ClassName
{
protected $db;
public function __construct($db)
{
$this->setConnection($db);
//Any other constructor things you want to happen...
}
/*
* This is just here for convenience, this could be protected if you only want to set
* the db connection via the constructor
*/
public function setConnection($db)
{
$this->db = $db;
}
public function test()
{
$val = $this->db->oneValue('SELECT first_name FROM users LIMIT 0, 1');
echo $val->first_name;
}
}
As mentioned in some comments above, this is a form of dependency injection which will give you more ability to re-use code inside your project (A Good Thing TM).
I prefer using singleton pattern for databases.
this is the DB class i am using for my app.
class Database {
protected static $_dbh;
const HOST = 'localhost';
const DATABASE = 'dbname';
const USERNAME = 'username';
const PASSWORD = 'password';
private function __construct() { }
public static function getInstance() {
if(!isset($_dbh)) {
try {
#Connection String.
self::$_dbh = new PDO('mysql:host='.self::HOST.';dbname='.self::DATABASE,self::USERNAME,self::PASSWORD);
self::$_dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
#Print Errors.
echo $e->getMessage();
}
}
return self::$_dbh;
}
}
as i am using singleton pattern the connection will be re-used. you can now use the connection everywhere in your app by calling static connection method i.e
class ClassName
{
protected static $_dbh;
public function __construct() {
self::$_dbh = Database::getInstance();
}
public function test() {
$sth = self::$_dbh->query('SELECT first_name FROM users LIMIT 0, 1');
$row = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $row['first_name'];
}
}

Using a database class in my user class

In my project I have a database class that I use to handle all the MySQL stuff. It connects to a database, runs queries, catches errors and closes the connection.
Now I need to create a members area on my site, and I was going to build a users class that would handle registration, logging in, password/username changes/resets and logging out. In this users class I need to use MySQL for obvious reasons... which is what my database class was made for.
But I'm confused as to how I would use my database class in my users class. Would I want to create a new database object for my user class and then have it close whenever a method in that class is finished? Or do I somehow make a 'global' database class that can be used throughout my entire script (if this is the case I need help with that, no idea what to do there.)
Thanks for any feedback you can give me.
Simple, 3 step process.
1/ Create a database object.
2/ Give it to your user class constructor.
3/ Use it in the user methods.
Little example.
File Database.class.php :
<?php
class Database{
public function __construct(){
// Connects to database for example.
}
public function query($sqlQuery){
// Send a query to the database
}
[...]
}
In User.class.php :
<?php
class User{
private $_db;
public function __construct(Database $db){
$this->_db = $db;
}
public function deleteUser(){
$this->_db->query('DELETE FROM Users WHERE name = "Bobby"');
}
}
Now, in userManager.php for example :
<?php
$db = new Database();
$user = new User($db);
// Say bye to Bobby :
$user->deleteUser();
If you want the current trendy name of this old technique, google "Dependency Injection". The Singleton pattern in php will fade away soon.
As he said, put all your functions in the database class and use the database object to access those functions from your user class. This should be the best method in your case.
Eg:
global $database;
userclassvar = $database->doSomething();
What I like to do is make the database class with the Singleton pattern in mind. That way, if you already have a database object, it just retrieves it, otherwise creates a new one. For example:
Database.class.php
class Db
{
protected static $_link;
private function __construct()
{
// access your database here, establish link
}
public static function getLink()
{
if(self::_link === null) {
new Db();
}
return self::_link;
}
// etc.
}
User.class.php
class User
{
protected $_link; // This will be the database object
...
public function __construct()
{
$this->_link = Db::getLink();
}
}
And now you can use User's $_link property to do the database functions, like $this->_link->query(...). You don't necessarily have to put the Db::getLink() in the constructor if your class doesn't have to interact with the database that much.
Since you are using the database as an object, why not just add methods to the object that your "users class" can employ to take care of the things it needs to do. The users class can contain a pointer to the database class. The database class will protect your database, and assure that the users class is using it appropriately.
Here is a solution using PDO.
<?php
class Database {
private static $dbh;
public static function connect() {
$host = "mysql:dbname=YOUR_DB_NAME;host=YOUR_DB_SERVER";
$username = "YOUR_USERNAME";
$password = "YOUR_PASSWORD";
try {
self::$dbh = new PDO( $host, $username, $password );
self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
self::$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch( PDOException $e ){
$error_message = $e->getMessage();
exit();
}
return self::$dbh;
}
}
class MYObject {
public static $dbh = null;
public function __construct(PDO $db = null) {
if($db === null){
$this->dbh = Database::connect();
} else {
$this->dbh = $db;
}
}
}
class User extends myObject {
public function __construct($id = null, PDO $db = null) {
if($db === null){
parent::__construct();
} else {
parent::__construct($db);
}
if($id !== null){
return $this->select($id);
}
}
public function select($id) {
$retVal =false;
try {
$stmt = $this->dbh->prepare("SELECT...");
$stmt->execute();
if( $stmt->rowCount()==1 ){
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$retVal =json_encode($row);
}
} catch (PDOException $e ) {
$error_message = $e->getMessage();
exit();
}
return $retVal;
}
}
?>
I think the better aproach would be to create the database class that instatiate right away on its own on a database.php and then include it on user.php. then every time you create a function that needs a database, you globalise the database object.
Check this.
databse.php
<?php
require_once ('includes/config.php');
class MysqlDb{
public $connection;
private $last_query;
private $magic_quotes_active;
private $real_escape_string_exists;
public function __construct() {
$this->open_connection();
$this->magic_quotes_active = get_magic_quotes_gpc();
$this->real_escape_string_exists = function_exists( "mysql_real_escape_string" );
}
public function open_connection() {
$this->connection = mysql_connect(DBHOST,DBUSER,DBPASS);
if(!$this->connection){
die("Could not Connect ".mysql_error());
}else{
$db = mysql_select_db(DB, $this->connection);
}
}
public function close_connection(){
if(isset($this->connection)){
mysql_close($this->connection);
unset($this->connection);
}
}
public function query($sql){
$this->last_query = $sql;
$results = mysql_query($sql, $this->connection);
$this->comfirm_query($results);
return $results;
}
private function comfirm_query($results){
if(!$results){
$output = "Query Failed " .mysql_error()."<br />";
$output .= "Last Query: " . $this->last_query;
die($output);
}
}
public function escape_value($value){
if( $this->real_escape_string_exists ) {
if($this->magic_quotes_active ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
} else {
if( !$this->magic_quotes_active ) { $value = addslashes( $value ); }
}
return $value;
}
public function fetch_array($results){
return mysql_fetch_array($results);
}
public function num_row($results){
return mysql_num_rows($results);
}
public function insert_id(){
return mysql_insert_id($this->connection);
}
public function affected_row(){
return mysql_affected_rows();
}
}
$database = new MysqlDb();
?>
here is the user.php
<?php
require_once ('includes/database.php');
class User {
public $id;
public $fName;
public $lName;
Public $userName;
public $password;
public $email;
public $acess;
public static function find_all(){
global $database;
return self::find_by_sql("SELECT * FROM users");
}
public static function find_by_id($id=0){
global $database;
$results_array = self::find_by_sql("SELECT * FROM users where id={$id}");
return !empty($results_array)? array_shift($results_array) : false;
}
public static function find_by_sql($sql){
global $database;
$results = $database -> query($sql);
$object_array = array();
while($row = $database -> fetch_array($results)){
$object_array[] = self::instantiate($row);
}
return $object_array;
}
public static function instantiate($row){
$user = new self;
foreach($row as $attribute => $value){
if($user -> has_attribute($attribute)){
$user -> $attribute = $value;
}
}
return $user;
}
private function has_attribute($attribute){
$object_vars = get_object_vars($this);
return array_key_exists($attribute, $object_vars);
}
}
?>

Categories