Reputation: 15
I want to querying with using this class:
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()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else {
$this->_error = true;
}
}
return $this;
}
I am trying to reach query method like this:
$sql = "SELECT * FROM name
WHERE namel LIKE :seek";
$db = DB::getInstance();
$db->query($sql, array(':seek' => $seek));
And I get this warning: Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\blabla\classes\DB.php on line 36
I even don't sure that my way for reaching DB class.
Upvotes: 0
Views: 111
Reputation: 6652
Update to your query fn() - issue was in your bindValue you need to pass param and value to bind
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
if(count($params)) {
foreach ($params as $param => $value) {
$this->_query->bindValue($param, $value);
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else {
$this->_error = true;
}
}
return $this;
}
Well it depends on your Like result, if you want it to display beginning and after you would have to update your value like so:
$this->_query->bindValue($param, '%' . $value . '%');
I don't know why you are returning $this.
Also if you are trying to get the result from outside the class, it needs to be public to access it.
public $_results;
Upvotes: 1