I have, in a db.php file, the following code:
public function query($sql, $params = array()){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)){
foreach($params AS $pa){
$this->_query->bindValue($x, $pa);
$x++;
}
}
#MASSIVE ERROR
#correctthis
if($this->_query->execute()){
echo 'success';
$this->_result = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_query = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
return $this;
}
public function error(){
return $this->_error;
}
My problem is that $this->_query->execute()
always is false, which means $_error is always being set to true. I can't get it to work, even though there doesn't seem to be anything wrong with it.
The script enters the prepare (I tested by echoing), which means it prepared successfully. It also enters the foreach loop so the values must be getting bound. But it just can't seem to execute. Why?
Edit:
I use DB::getInstance()->query("SELECT email FROM user_credentials WHERE user_id = ?", array(1))
to call the query, and this is what getInstance looks like:
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DB();
}
return self::$_instance;
}
Make your function this way
public function queryAll($sql, $params = array(), $method = PDO::FETCH_OBJ)
{
$stmt = $this->_pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll($method);
}
or, if you prefer method chaining, then this way
public function query($sql, $params = array())
{
$stmt = $this->_pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
Then set PDO in exception mode, and you will be always informed of any error occurred. To so so add this code in constructor
$this->_pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
The rest of your code is useless, inflexible, error-prone and sometimes plainly wrong.
Try this to know the specific error returned by the query. I have only modified the else block.
#MASSIVE ERROR
#correctthis
if($this->_query->execute()){
echo 'success';
$this->_result = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_query = $this->_query->rowCount();
} else {
$this->_error = true;
echo $this->_query->errorInfo()[2];
}
I think you are not properly connected with the database. See if the connecting function is working properly. Something like the code below if you are trying this from an online tutorial:
$this->_pdo = new PDO('mysql:host=' . Config::get
('mysql/host') . ';dbname=' . Config::get('mysql/db'),
Config::get('mysql/username'), Config::get('mysql/password'));