Error while adding PDO to my code - php

I have connection.php file where i am initializing PDO in the $db.
And i want to check this validation in the User.php which i include after connection.php.
but it is giving me error .
try {
$db = new PDO("mysql:dbname=$db_name;host=$db_host", $db_username,$db_password);
echo "PDO connection object created";
}
catch(PDOException $e){
echo $e->getMessage();
}
How can i validate this code by executing PDO.
How i will pass the PDO to the User Class..
Fatal error: Call to a member function query() on a non-object in /var/www/youngib/rahul/yapi/user.php on line 41
$sql="select * from users where email='$this->email'";
$rs=$db->query($sql);
if(mysql_num_rows($rs)>0){
$msg=geterrormsg(4);
//email already exist
echo $msg= "{ 'success': 'false','msg':'$msg' ,'error_code':'4' }";
return false;
}
Please Help.
Thanks .

Inject it in to the class or make a singleton DB class like...
Injection:
class User
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function getDb()
{
return $this->db;
}
public function isUser($email)
{
$stmt = $this->getDb()->prepare('select count(email) as user_exists from users where email = :email');
return (bool) $stmt->execute(array(':email' => $email))->fetchColumn();
}
}
Singleton:
class Database {
protected $pdo;
protected static $instance;
protected function __construct($dsn, $user, $password)
{
$this->pdo = new PDO($dsn, $user, $password);
}
public static function getInstance()
{
if(!self::$instance)
{
// normally you would load the dsn, user, and password from a config file
$db = Config::get('db');
self::$instance = new self($db['dsn'], $db['user'], $db['password']);
}
return self::$instance;
}
public function getDb()
{
return $this->pdo;
}
}
class User
{
protected $db;
public function __construct(PDO $db = null)
{
if(null !== $db)
{
$this->db = $db;
}
}
public function getDb()
{
if(!$this->db)
{
$this->db = Database::getInstance()->getDb();
}
return $this->db;
}
public function isUser($email)
{
$stmt = $this->getDb()->prepare('select count(email) as user_exists from users where email = :email');
return (bool) $stmt->exectute(array(':email' => $email))->fetchColumn();
}
}

I hate to say this, but try just adding
global $db;
before your $db->query($sql); line. It might work, depending on exactly where the $db was created.
That said, prodigitalson's answer is a vastly improved approach, it just involves fixing your entire design, which involves more up front work :)

Related

Is die function accept only strings?

this code works:
if (isset($db->error)) {
echo $db->error;
}
This code in not working:
if (isset($db->error)) {
die($db->error);
}
This is my DB class:
class Db {
private $db,
$error;
public function __construct() {
return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
}
}
"D_NAME" is wrong so an error appears but I didn't kill the page, content still appear after the error. Why? Thanks!
The if block in the constructor is never executed, because you are returning $this->db:
public function __construct() {
return $this->db = new mysqli(DB_SERVER, DB_USER, DB_PASS, D_NAME);
// the lines after return will never be executed!
}
This is the first reason why the $db->error is unset.
The second reason is that the $error member is private, which means that you are not allowed to access this property directly. So you should make it accessible in one of the following ways (at least):
make it public;
implement the __get and __isset magic methods;
implement a getter method.
Using public $error
class Db {
private $db;
public $error;
public function __construct() {
$this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
return $this->db;
}
}
$db = new Db;
if (isset($db->error)) {
die($db->error);
}
echo 'xxx', PHP_EOL;
Using __isset and __get magic methods
class Db {
private $db;
private $error;
public function __construct() {
$this->db = new mysqli('localhost', 'sss3', 'a4J1uQzQCasD', 's3_small');
if ($this->db->connect_error) {
$this->error = $this->db->connect_error;
}
return $this->db;
}
public function __get($key) {
if ($key === 'error') {
return $this->error;
}
}
public function __isset($key) {
if ($key === 'error') {
return isset($this->error);
}
}
}
$db = new Db;
if (isset($db->error)) {
die($db->error);
}
echo 'xxx', PHP_EOL;
Implementing a getter method
A getter method is just a method returning value of a private member. In our case it is $error. So you might leave it private, but add a method to access its value. For instance:
public function getError() {
return $this->error;
}

Unable to add values with bindValue() to a pdo object

I'm writing a registration script that checks if the username already exists.
First I had troubles getting my database instance from databaseconnection.php to registration.php, this was the error: Call to undefined method DatabaseConnection::prepare().
But now I'm getting past the prepare() line and want to give my values to the query with bindValue(), but this next error is what I get 'Call to a member function bindValue() on a non-object'.
Does this still means I didn't get the correct database instance but a instance of the databaseconnection.php class?
This is databaseconnection.php
<?php
class DatabaseConnection {
private static $instance = null;
public $db_connection;
private function __construct(){
try{
$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME, DB_USER, DB_PASS);
$this->db_connection->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
return true;
} catch (PDOException $exception){
$this->errors[] = $this->lang['Database error'];
return false;
}
}
public static function getInstance(){
if(self::$instance === null){
self::$instance = new DatabaseConnection();
}
return self::$instance;
}
public function __call($method, $args) {
$callable = array($this->pdo, $method);
//is_callable, verify that the contents of a variable can be called as a function
if(is_callable($callable)) {
return call_user_func_array($callable, $args);
}
}
}
?>
In registration.php I use this code to get the instance into my local private variable:
class Registration
{
private $db_connection = null;
public function __construct()
{
$this->db_connection = databaseConnection::getInstance();
...
}
...
}
And would like to be able to execute this query in registration.php:
...
$check_username_query = $this->db_connection->prepare('SELECT user_name, user_email FROM users WHERE user_name=:user_name OR user_email=:user_email');
$check_username_query->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$check_username_query->bindValue(':user_email', $user_email, PDO::PARAM_STR);
$check_username_query->execute();
$results = $check_username_query->fetchAll();
...
$callable = array($this->pdo, $method);
You have instance of PDO in $this->db_connection not $this->pdo

Can't use prepare() when using mysqli prepared statements

I'm tryign to create an object orientated approach to a project I'm working on for fun, but I'm having trouble getting my head around the idea of a database class. I'm getting the following error.
Call to undefined method Database::prepare()
Database Class
class Database
{
protected $connection;
function __construct()
{
$this->createConnection();
}
private function createConnection()
{
$this->connection = new mysqli("localhost", "user", "password", "test");
if ($this->connection->connect_errno)
{
echo "Failed to connect to MySQL: (" . $this->connection->connect_errno . ") " . $this->connection->connect_error;
}
else
{
echo 'Connected to database.<br />';
}
}
}
$db = new Database();
UserActions Class
class userActions
{
protected $_db;
protected $_username;
protected $_password;
protected $_auth;
protected $tableName;
function __construct($db, $username, $password, $auth)
{
$this->_db = $db;
$this->_username = $username;
$this->_password = $password;
$this->_auth = $auth;
$this->checkUserExists();
}
private function checkUserExists()
{
$query= "SELECT COUNT(*) FROM '{$this->tableName}' WHERE username = ?";
$stmt = $this->_db->prepare($query);
$stmt->bind_param('s', $this->username);
$userNumber= $stmt->execute();
echo $userNumber;
}
}
What am I doing wrong, could I do anything to improve the way I'm going about this task?
You need to add the following method to your class:
public function prepare($query) {
return $this->connection->prepare($query);
}
You could define a magic method for your class that automatically passes any undefined method to the connection:
public function __call($name, $arguments) {
return call_user_func_array(array($this->connection, $name), $arguments);
}

Unable to use PDO methods when using DB class

Hey guys I'm doing this wrong again I'm sure, but I'm trying to instantiate a PDO database
handler from my class Database from the file class.database.php inside my class AdminSession
from class.admin.php, somethings a bit screwy with my dependancy injection, and it is not
allowing me to use PDO's methods corretly; like fetch(), prepare() etcetra.
the class.database.php file
class Database
{
public $db; // handle of the db connection
private static $dsn="mysql:host=server2.com;dbname=database";
private static $user="user";
private static $pass="pass";
private static $instance;
public function __construct ()
{
$this->db = new PDO(self::$dsn,self::$user,self::$pass,$self::$opts);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
switch($_SERVER['ENVIRONMENT']) {
case 'staging':
self::$dsn="mysql:host=server1.com;dbname=database";
self::$user="user";
self::$pass="pass";
break;
default:
self::$dsn="mysql:host=server2.com;dbname=database";
self::$user="user";
self::$pass="pass";
}
}
public static function getInstance()
{
if(!isset(self::$instance))
{
$object= __CLASS__;
self::$instance=new $object;
}
return self::$instance;
}
}
and here's the topmost of my class.admin.php, and a method that is throwing an error.
right now the errors I'm getting
PHP Fatal error: Call to undefined method line 230
If I use $this->db-prepare($sql)
or
PHP Fatal error: Call to a member function prepare() on a non-object line 230
If I use $db-prepare($sql)
require('library/class.database.php');
class AdminSession {
static $abs_path;
public function __construct(Database $db) {
session_start();
self::$abs_path = dirname(dirname(__FILE__));
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->post = $_POST; // filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if(get_magic_quotes_gpc ()) {
//get rid of magic quotes and slashes if present
array_walk_recursive($this->post, array($this, 'stripslash_gpc'));
}
}
$this->get = $_GET; // filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
array_walk_recursive($this->get, array($this, 'urldecode'));
}
// other methods
private function checkDB($username, $password) {
$sql = "SELECT * FROM users WHERE username=:username";
try {
$db = Database::getInstance();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $username);
$stmt->execute();
$user = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if($user) {
//general return
if(is_object($user[0]) && md5($user[0]->password) == $password) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
}
You can't put logic into your class definition. Instead, determine the value of these variables within the constructor. The switch will work in a method, but not when defining members.
Edit: I actually feel silly for missing this. The connection was made before the switch statement. I don't know that it'll fix the second set of issues ... but it'll behave properly for the original question now.
class Database
{
public $db; // handle of the db connection
private static $opts = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
private static $dsn="mysql:host=server2.com;dbname=database";
private static $user="user";
private static $pass="pass";
private static $instance;
public function __construct ()
{
switch($_SERVER['ENVIRONMENT']) {
case 'staging':
self::$dsn="mysql:host=server1.com;dbname=database";
self::$user="user";
self::$pass="pass";
break;
default:
self::$dsn="mysql:host=server2.com;dbname=database";
self::$user="user";
self::$pass="pass";
}
$this->db = new PDO(self::$dsn,self::$user,self::$pass,$self::$opts);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public static function getInstance()
{
if(!isset(self::$instance))
{
$object= __CLASS__;
self::$instance=new $object;
}
return self::$instance;
}
}

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