I am attempting to do an if statement to populate the correct navigation menu for different levels of permission users.
I have a class called users, which has the following function called 'hasPermission':
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return true;
}
}
return false;
}
Which works off the following groups in my database:
Then in a different file, I am trying to get the current user's signed in permission with $permission (I think the error is in here) and then use the if statement to populate the correct file.
$permission = $user->hasPermission($group);
if($permission == 'User') {
include 'nav/userNav.php';
} else if ($permission == 'Admin') {
include 'nav/adminNav.php';
}
Does anyone see what I am doing wrong?
EDIT:
User class full code:
<?php
class User {
private $_db,
$_data,
$_sessionName,
$_cookieName,
$_isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('session/session_name');
$this->_cookieName = Config::get('remember/cookie_name');
if(!$user) {
if(Session::exists($this->_sessionName)) {
$user = Session::get($this->_sessionName);
if($this->find($user)) {
$this->_isLoggedIn = true;
} else {
// process Logout
}
}
} else {
$this->find($user);
}
}
public function update($fields = array(), $id = null) {
if(!$id && $this->isLoggedIn()) {
$id = $this->data()->id;
}
if(!$this->_db->update('users', $id, $fields)) {
throw new Exception('There was a problem updating!');
}
}
public function create($fields = array()) {
if(!$this->_db->insert('users', $fields)) {
throw new Exception('There was a problem creating an account:' . $this->_db->errorMessage());
}
$this->lastId = $this->_db->lastInsertId();
}
public function find($user = null) {
if($user) {
$field = (is_numeric($user)) ? 'id' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count()) {
$this->_data = $data->first();
return true;
}
}
return false;
}
public function login($username = null, $password = null, $remember = false) {
if(!$username && !$password && $this->exists()) {
Session::put($this->_sessionName, $this->data()->id);
} else {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
//if(Auth::check($this->data()->password, $password)){
Session::put($this->_sessionName, $this->data()->id);
if($remember) {
$hash = Hash::unique();
$hashCheck = $this->_db->get('users_session', array('user_id', '=', $this->data()->id));
if(!$hashCheck->count()) {
$this->_db->insert('users_session', array(
'user_id' => $this->data()->id,
'hash' => $hash
));
} else {
$hash = $hashCheck->first()->hash;
}
Cookie::put($this->_cookieName, $hash, Config::get('remember/cookie_expiry'));
}
return true;
}
}
}
return false;
}
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return true;
}
}
return false;
}
public function exists() {
return (!empty($this->_data)) ? true : false;
}
public function logout() {
$this->_db->delete('users_session', array('user_id', '=', $this->data()->id));
Session::delete($this->_sessionName);
Cookie::delete($this->_cookieName);
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
?>
EDIT #2 - Trying to create a new function for this:
public function getGroup($groupkey) {
$group_name = $this->_db->get('groups', array('name'));
}
Then in the other file where I am trying to call this:
$permission = $user->getGroup($group_name);
if($permission == 'User') {
include 'nav/userNav.php';
} else if ($permission == 'Admin') {
include 'nav/adminNav.php';
}
Edit #3
With this code:
public function getGroup($groupkey) {
$group_name = $this->_db->get('groups', array('name'));
return $group_name;
}
I get this erorr:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function User::getGroup(), 0 passed in /home/house/public_html/admin/index.php on line 322 and exactly 1 expected in /home/house/public_html/classes/User.php:116 Stack trace: #0 /home/house/public_html/admin/index.php(322): User->getGroup() #1 {main} thrown in
Action function in DB class.
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} ?";
$date = new DateTime();
file_put_contents('debug_log', "\n[{$date->format('Y-m-d H:i:s')}] $sql", FILE_APPEND);
$results = $this->query($sql, array($value));
file_put_contents('debug_log1', "\n[{$date->format('Y-m-d H:i:s')}] $sql" . print_r($results, 1), FILE_APPEND);
return $this;
}
}
return false;
}
EDIT - FULL DB CLASS
<?php
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0,
$_errmsg = "";
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'));
/*$host = config::get('mysql/host');
$database = config::get('mysql/db');
$username = config::get('mysql/user');
$password = config::get('mysql/password');
$dbh = new PDO('mysql:host='.$host.';dbname='.$database.', $username, $password);*/
} catch(PDOException $e) {
die($e->getMEssage());
}
}
//**********LastID
public function lastInsertId () {
return $this->_pdo->lastInsertId();
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()){
"DEBUG DB::query called<br>SQL: $sql<br><br>PARAMS: " . implode("<br>", $params) . "<hr>\n";
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
"DEBUG: prepared statement created ok<hr>\n";
$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();
"DEBUG: query succeeded, rowcount was: " . $this->_count . "<hr>\n";
} else {
"DEBUG: query failed to execute, reason:<br>" . implode( "<br>", $this->_query->errorInfo() ) . "<hr>\n";
$this->_error = true;
}
} else {
"DEBUG: Failed to create prepared statement<hr>\n";
}
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} ?";
$date = new DateTime();
file_put_contents('debug_log', "\n[{$date->format('Y-m-d H:i:s')}] $sql", FILE_APPEND);
$results = $this->query($sql, array($value));
file_put_contents('debug_log1', "\n[{$date->format('Y-m-d H:i:s')}] $sql" . print_r($results, 1), FILE_APPEND);
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 = '';
$x = 1;
foreach($fields as $field) {
$values .= '?';
if($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) Values ({$values})";
return ! $this-> query($sql, $fields)->error();
}
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}";
return ! $this-> query($sql, $fields)->error();
}
public function results() {
return $this->_results;
}
public function first() {
return $this->results()[0];
}
public function error() {
return $this->_error;
}
public function errorMessage() {
return $this->_errmsg;
}
public function count(){
return $this->_count;
}
}
?>
Based on the updated information, I can see that you're using PDO and executing fetchALL and returning results as an array of stdClass objects (FETCH_OBJ). Not sure why you're storing permission at all, let alone as a JSON object but thankfully, we don't need that column in this case. We can simply look up name based on id.
It is important to realize that $this->_db->get(... returns an instance of your DB class (or false) so you should name your variable appropriately, $db. Let me know if you run into any issues and I'll try to help out.
<?php
/**
* Returns the role name of the currently logged in user. If no role can be
* determined, an empty string will be returned.
* #return string
*/
public function getGroup()
{
$role = '';
// I really can't tell what `$this->data()->group` is but
// I'm making the assumption that it is the logged in user's role ID.
$db = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($db->count() > 0) {
// `first()` returns the first element of the results as a stdClass object.
// https://www.geeksforgeeks.org/what-is-stdclass-in-php/
$role = $db->first()->name;
}
return $role;
}
...
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return $key;//change true here to the role
}
}
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();
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
I have tried my best to find out the result on my own, but have failed.
Here's the source code that I have tried at my level best.
<?php
class DataBase
{
private $connect;
private $dbUser;
private $dbHost;
private $dbPassword;
private $dbDatabase;
private $numRows;
private $results;
public function connect($host, $username, $pass, $db)
{
$this->dbHost = $host;
$this->dbUser = $username;
$this->dbPassword = $pass;
$this->dbDatabase = $db;
return $this->connect = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbDatabase);
}
public function disConnect($connect) {
return mysqli_close($this->connect = $connect);
}
public function select($table, $where = array(), $orderBy = NULL) {
if (count($where) === 3) {
$operators = array('=', '<', '>', '>=', '<=', 'LIKE');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$query = "SELECT * FROM {$table} WHERE '". $field . $operator . $value . "'";
}
if (mysqli_query($this->connect, $query)) {
return true;
} else {
die(mysqli_error($this->connect));
}
}
}
public function countRows($queryRes)
{
if (mysqli_num_rows($queryRes) > 0) {
return true;
} else {
return false;
}
}
}
I get the error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\Practice\index.php on line 70
and line 70 is: if (mysqli_num_rows($queryRes) > 0) {
Here's where and how I call the method:
$suc = "";
if (isset($_POST['btnSubmit'])) {
$con = new DataBase();
$objDb = $con->connect('localhost', 'root', '', 'practice');
$username = $_POST["username"];
$suc = $con->select('users', ['username', 'LIKE', '%'.$username.'%']);
if ($suc) {
print_r($con->countRows($suc));
} else {
echo "Unable to Find Record !";
}
//print_r($suc);
$con->disConnect($objDb);
}
?>
Kindly guide me where am I making the mistake.
Thanks
function countRows($sql)
{
$rst = #mysql_query($sql)or trigger_error("SQxxxL", E_USER_ERROR);
return $numrows = mysql_num_rows($rst);
}
You have $numRows class property. Why you are not using it?
Set query number of rows count into $this->numRows property.
Change your select() method:
public function select($table, $where = array(), $orderBy = NULL) {
if (count($where) === 3) {
$operators = array('=', '<', '>', '>=', '<=', 'LIKE');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$query = "SELECT * FROM {$table} WHERE '". $field . $operator . $value . "'";
}
$result = mysqli_query($this->connect, $query);
if ($result) {
$this->numRows = mysqli_num_rows($result);
return true;
} else {
die(mysqli_error($this->connect));
}
}
}
And change your countRows() method like yhis:
public function countRows($queryRes)
{
return $this->numRows == 0 ? false : true;
}