I have looked at all of the other questions asked on SO and had no luck finding the problem in my code. I am trying to update a Database with an Update() method. My Insert() method is up and running, but I receive the above error when I run the code. It seems to be an error when binding my values. Would someone please give me some advice? Thank you.
<?php
class DB{
private static $_instance = null;
private $_pdo,$_query,$_error = false, $_result, $_count = 0, $_lastInsertID = null;
private function __construct(){
try{
$this->_pdo = new PDO('mysql:host='.DB_HOST.';port=3307;dbname='.DB_NAME , DB_USER, DB_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 = []){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
//binds paramaters
$x = 1;
if(count($params)){
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if ($this->_query->execute()){
$this->_result = $this->_query->fetchALL(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
$this->_lastInsertID = $this->_pdo->lastInsertId();
} else{
$this->error = true;
}
}
return $this;
}
public function insert($table,$fields=[]){
$fieldString = '';
$valueString = '';
$values = [];
foreach( $fields as $field => $value){
$fieldString .= '`'. $field . '`,';
$valueString .= '?,';
$values[] = $value;
}
$fieldString = rtrim($fieldString, ',');
$valueString = rtrim($valueString, ',');
$sql = "INSERT INTO {$table} ({$fieldString}) VALUES ({$valueString})";
if(!$this->query($sql, $values)->error()){
return true;
}else{
return false;
}
}
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
public function error(){
return $this->_error;
}
}
?>
<?php
class Home extends Controller{
public function __construct($controller,$action){
parent::__construct($controller, $action);
}
public function indexAction(){
//die('welcome to the home controller this is the index action.');
$db = DB::getInstance();
$fields = [
'fname'=> 'Jared',
'email'=>'JBowser#123.com'];
//$contacts = $db->insert('contacts',$fields); This is how we insert to our DB.
$contacts = $db->update('contacts',3, $fields); // This is how we update our DB.
$this->view->render('home/index'); ///path from views directory **
}
}
You dont load the values array in the Update method
public function update($table, $id, $fields = []){
$fieldString = '';
$values = [];
foreach($fields as $field => $value){
$fieldString .= ' ' . $field . ' = ?,';
$values[] = $value; // <<-- Added this line
}
$fieldString = trim($fieldString);
$fieldString = rtrim($fieldString, ',');
$sql = "UPDATE {$table} SET {$fieldString} WHERE id = {$id}";
$obj = $this->query($sql,$values);
dnd($obj);
if(!$this->_query($sql,$values)->error()){
return true;
}
return false;
}
Related
I am using this PHPAuth from this github link: https://github.com/PHPAuth/PHPAuth. Using this tutorial I am trying to make a registration system.
Now, I am getting following error message when I check a field value already exists in the database table:
Fatal error: Uncaught Error: Call to a member function count() on boolean ........... Stack trace: #0 ...........: Validate->check(Array, Array) #1 {main} thrown in ......\admin\classes\Validate.php on line 41
I am checking with following code:
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()) {
$this->addError("{$item} already exists.");
}
break;
DB.php page:
<?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/database'), 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;
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count ($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function delete($table, $where) {
return $this->action('DELETE ', $table, $where);
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function results() {
return $this->_results;
}
public function first() {
$data = $this->results();
return $data[0];
}
public function count() {
return $this->_count;
}
public function error() {
return $this->_error;
}
}
Is there anything I am doing wrong? How can I solve it?
I'm trying to loop through a result set and print out the values of the rows using PDO with my PHP database wrapper that I made using a tutorial. When I'm using PDO functions like fetchAll(); or fetch(); I get fatal errors.
I'm just curious how I can do this with the code I've provided. I can use the code below to easily implement insert, updates to data etc but I'm having a hard time figuring out how to just loop and print. Any help would be amazing thanks.
The I need help with is the getOffers function in the bottom block of code.
I have a DB.php file:
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;
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = $sql = "{$action} FROM `{$table}` WHERE {$field} {$operator} '{$value}'";;
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
//deletes items from the database
public function delete($table, $where) {
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array()) {
//check if fields has any data
if(count($fields)) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= "?";
//check if x is less than the count of fields
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
public function update($table, $id, $fields) {
$set = '';
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE `id` = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
return $this->_results;
}
public function first() {
return $this->results()[0];
}
public function error() {
return $this->_error;
}
public function count() {
return $this->_count;
}
}
And I have Offer.php:
<?php
class Offer {
private $_db,
$_data;
public function __construct() {
$this->_db = DB::getInstance();
}
public function createOffer($fields = array()) {
//If the offer is not entered into the database
if(!$this->_db->insert('offers', $fields)) {
throw new Exception('There was a Problem creating the offer.');
}
}
public function getOffers() {
$offers = $this->_db->get('offers', array('address', '=', 'Los Angeles'));
$result = $offers->fetchAll();
print_r($result);
}
}
?>
It seems in Offer.php it should be
$result = $offers->results();
not
$result = $offers->fetchAll();
Im using OOP and im new with that. I just dont get it...i tryed everything and i just can't make a simple text edit, for ex:
I want to make a form where i can edit text from main page. So for ex i want to edit footer text "copyright by bla bla" i want to edit that by using simple form. It sounds easy but for me with oop...its not that much.
This is example of my register/login system and i tryed to make it similar to this but can't figure it out.
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;
}
public function action($action, $table, $where = array()){
if(count($where) === 3){
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()){
return $this;
}
}
}
return false;
}
public function get($table, $where){
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array()){
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field){
$values .= '?';
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
return false;
}
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach($fields as $name => $value){
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()){
return true;
}
return false;
}
public function results(){
return $this->_results;
}
public function first(){
return $this->results()[0];
}
public function error(){
return $this->_error;
}
public function count(){
return $this->_count;
}
}
This is database class:
DB.php
<?php
class DB {
public static $instance = null;
private $_pdo = null,
$_query = null,
$_error = false,
$_results = null,
$_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(PDOExeption $e) {
die($e->getMessage());
}
}
public static function getInstance() {
// Already an instance of this? Return, if not, create.
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;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where) {
return $this->action('DELETE', $table, $where);
}
public function action($action, $table, $where = array()) {
if(count($where) === 3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
return false;
}
}
public function insert($table, $fields = array()) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $value) {
$values .= "?";
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function update($table, $id, $fields = array()) {
$set = null;
$x = 1;
foreach($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)) {
$set .= ', ';
}
$x++;
}
$sql = "UPDATE users SET {$set} WHERE id = {$id}";
if(!$this->query($sql, $fields)->error()) {
return true;
}
return false;
}
public function results() {
// Return result object
return $this->_results;
}
public function first() {
return $this->_results[0];
}
public function count() {
// Return count
return $this->_count;
}
public function error() {
return $this->_error;
}
}
I was looking this database approach and it seems very practical and useful. I'm beginner at oop and still learning. The requestQuote would look something like this:
How do I bindParam in query like this?
requestQuote = DB::getInstance()->query(""); (form DB.class)
This is code I have right now:
$request = "";
if ($_POST) {
$request = $_POST["request"];
} else if (isset($_GET["request"])) {
$request = $_GET["request"];
}
$requestQuote="%" . $request . "%";
$sql = $conn -> prepare("SELECT * FROM users WHERE concat(name, ' ',lastname, ' ', user_id) LIKE :request limit " . (($page * 50)-50) . ",50");
$sql->bindParam(":request", $requestQuote);
$sql -> execute();
$results = $sql -> fetchAll(PDO::FETCH_OBJ);
When I put it like this, then pagination works. But I need search form... and that won't work...
$sql= DB::getInstance()->query(
"SELECT * FROM users
WHERE (category='admin')
LIMIT " . (($page* 5)-5) . ",5");
#Paul was close but you got one more issue:
Check this part of the class:
$x = 1;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x, $param);
$x++;
}
}
It is not binding with named place holder, you need to change the code:
$limit = ($page * 50)-50;
$params = array('%lolcats%', $limit);
$query =
"SELECT * FROM users
WHERE concat(name, ' ',lastname, ' ', user_id)
LIKE ?
LIMIT ?,50";
$results = DB::getInstance()->query($query, $params);
or change the class code to bind by placeholder, something along the following lines:
#$params = array(':request' =>'%lolcats%', ':limit'=>$limit);
if(count($params)) {
foreach($params as $key=>$value) {
$this->_query->bindValue($key, $value);
}
}
Looking at this class, the second argument of query function is an optional array of parameters so use this to pass the parameters for your request:
$params = array(':request' => 'lolcats');
$limit = $page - 1 * 50;
$query = sprintf(
"SELECT * FROM users
WHERE concat(name, ' ',lastname, ' ', user_id)
LIKE :request
LIMIT %d,50",
$limt
);
$results = DB::getInstance()->query($query, $params);
I have a very simple select query using pdo but it is not working.
The generic sql query is
$sql = "select * from table where type != 'address' and type != 'multipleimage'";
Now in pdo I have
$fieldtype = array('address','multipleimage');
$query = $this->db->prepare("SELECT * from table where
(type not in $type) and (userid !=:userid) ");
$query->execute(array(':userid' => 2, $fieldtype ));
Now getting notice + warning
Notice is ' Array to string conversion....'
Warning is 'Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation.....'
Why don't you use NOT IN clause like:
$sql = "select * from table where type not in ('address','multipleimage')";
Something like this, you may have to do some minor changes
<?php
$fieldtype = array('address','multipleimage');
$inQuery = implode(',', array_fill(0, count($fieldtype), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'select * from table where type not in(' . $inQuery . ')'
);
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $fieldtype);
$stmt->execute();
?>
I have created my own ORM like class called DBConnection.php. It does all CRUD functionalities for any table in the specified database. It uses PDO as well. Feel free to play with it, customize and use in your code if you would like to....
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of DBConnection
*
* #author alemayehu
*/
require_once '../lib/PHPDebug.php';
class DBConnection {
private static $_instance = null;
private $_pdo;
private $_query;
private $_error = false;
private $_results;
private $_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 (Exception $ex) {
PHPDebug::printLogText("Connection Failed : ". $ex->getMessage() , "../lib/debug.txt");
die($ex->getMessage());
}
}
public static function getInstance(){
if(!isset(self::$_instance)){
self::$_instance = new DBConnection();
}
return self::$_instance;
}
public function fetchResultSet($sql, $params = array()){
//var_dump($params);passed
$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++;
}
}else{
echo 'something wrong with the array';
}
var_dump($this->_query);
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}else{
$this->_error = true;
}
}
return $this->_results;
}
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;
}
public function error(){
return $this->_error;
}
private function action($action, $table, $where = array()){
if(count($where) === 3){
$operators = array('=', '<', '>', '<=', '>=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if( !$this->query($sql, array($value))->error() ){
return $this;//was this
}
}
}
}
public function get($table, $where){
return $this->action('SELECT *', $table, $where);
}
public function delete($table, $where){
return $this->action('DELETE', $table, $where);
}
public function insert($table, $fields = array()){
if(count($fields)){
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach($fields as $field){
$values .= '?';
if($x < count($fields)){
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES( {$values} )";
//var_dump($sql);
if( ! $this->query($sql, $fields)->error()){
return true;
}
}
return false;
}
public function update($table, $id, $fields){
$set = '';
$x = 1;
foreach ($fields as $name => $value) {
$set .= "{$name} = ?";
if($x < count($fields)){
$set .= ', ';
}
$x++;
}
$sql = "UPDATE {$table} SET {$set} WHERE user_id = {$id}";
if(! $this->query($sql, $fields)->error()){
return true;
}else{
return false;
}
}
public function fetchAllRecords($table, $where){
return $this->query("SELECT * FROM {$table} WHERE $where");
}
public function count(){
return $this->_count;
}
public function getResults(){
return $this->_results;
}
public function first(){
return $this->_results[0];
}
}//end class