I am trying to execute a query by binding parameters. I have a query() function in DB.php, which takes the query and parameters as arguments. In this function, the query is successfully prepared using prepare(), but the query is not executed when i am using execute() on it.(I am not getting "Success" printed on the screen.)
What should i do? So that the the query gets executed successfully.
Code:
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/password'));
} 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, $param);
$x++;
}
}
if ($this->_query->execute()) {
echo "Success";
}
}
}
}
index.php
<?php
require_once 'core/init.php';
DB::getInstance()->query("SELECT username FROM users WHERE username = ?", array('alex'));
$this->_query->execute()because the$this->_pdo->prepare($sql)call fails.print_r($this->_query->errorInfo())in else statement the output shows Array ( [0] => 3D000 [1] => 1046 [2] => No database selected )$this->_query->execute($params).