3

am new to PHP-OOP and working with the pdo am getting the following errors

Warning: PDO::__construct() expects parameter 3 to be string, array given in C:\xampp\htdocs\ooplogin\classes\DB.php on line 12

connected

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\ooplogin\classes\DB.php on line 28

Here's my /db.php

<?php
class DB{
	private static $_instance = null;
	private $_pdo, 
			$_query, 
			$_error = false, 
			$_results, 
			$_count = 0;

	private function __construct(){
		try {
			$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname='. Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/passsword'));
			echo "connected";
		} catch (PDOException $e) {
			die($e->getMessage());
		}
	}

	public static function getInstance() {
		if (!isset(self::$_instance)) {
			self::$_instance = new DB();
		}
		return 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 as $param) {
					$this->_query->bindValue($x, $params);
					$x++;
				}
			}

			if ($this->_query->execute()) {
				$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
				$this->_count = $this->_query->rowCount();
			} else {
				$this->_error = true;
			}
		}
		return $this;
	}
	public function error(){
		return $this->_error;	
	}
}
config.php

<?php
class Config{
	public static function get($path = null){
		if($path){
			$config=$GLOBALS['config'];
			$path = explode('/',$path);

			foreach ($path as $bit) {
				if(isset($config[$bit])){
					$config = $config[$bit];					
				}
			}
			return $config;
		}
		return false;
	}
}
init.php

<?php
session_start();

$GLOBALS['config'] = array(
		'mysql' =>array(
			'host' => '127.0.0.1',
			'username'=>'root',
			'password' =>'',
			'db' =>'spyroll'
		),
		'remember' =>array(
			'cookie_name' =>'hash',
			'cookie_expiry' =>604800
		),
		'session' =>array(
			'session_name' => 'user'
		)
	);

spl_autoload_register(function($class){
	require_once 'classes/'. $class . '.php';
});

index.php

<?php
require_once 'core/init.php';

$user = DB::getInstance()->query("SELECT username FROM users WHERE username = ?", array('alex'));

if($user->error()) {
	echo 'no user';
} else {
	echo 'OK!';
}

}

Thanks a ton in advance for your help. I really need to solve this as soon as possible. -syed

6
  • Your Config::get() is returning an array, but the connection requires a string like localhost. Then the fatal error happens because your connection has failed. Commented Jan 26, 2015 at 5:26
  • That Config class/method seems a bit elaborate for just putting in PDO credentials. Can't you just simply put the connection credentials in manually? Commented Jan 26, 2015 at 5:30
  • For instance, in the __construct() of the DB class, just write manually the db info like: __construct($host = 'localhost',$username = 'username',$password = 'password',$dbname = 'db_name') Commented Jan 26, 2015 at 5:32
  • 1
    You have a typo in Config::get('mysql/passsword') -- too many ss. Any chance that's all it is? Commented Jan 26, 2015 at 5:34
  • I suggest use idiorm.readthedocs.org/en/latest instead your class DB, because it contain all needed actions. Just try it:) Commented Jan 26, 2015 at 9:08

1 Answer 1

0

There is just a typo in your password request. Try

$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname='. Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/password'));

instead of

$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') . ';dbname='. Config::get('mysql/db'), Config::get('mysql/username'), Config::get('mysql/pass**s**word'));

What happens? If your "config path" is not found, your Config::get method returns the full configuration array. Maybe you can throw an exception if the key is not found... or you return false (as you also do if $path is not given):

<?php
class Config{
    public static function get($path = null){
        if($path){
            $config=$GLOBALS['config'];
            $path = explode('/',$path);

            $result = false;
            foreach ($path as $bit) {               
                if(isset($config[$bit])){
                    $result = $config[$bit];                    
                }
            }
            return $result;
        }
        return false;
    }
}

Also your Config::get method does not make sense in this case. It is not able to handle more complex arrays, but it is too complex to handle such simple 2-dimensional arrays. Maybe you can use a method like Config::get($key, $value)?

<?php
class Config{
    public static function get($key, $value){
        if (isset($GLOBALS['config'][$key]) && isset($GLOBALS['config'][$key][$value]))
            return $GLOBALS['config'][$key][$value];
        else {
            trigger_error('Unknown configuration entry.', E_USER_WARNING);
            return false;
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot.. for all the helpful tips.. really appreciate it...! please if you get time can u help me with this.. link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.