I'm following this tutorial https://www.youtube.com/watch?v=zvXgsouIzVg&t=15310s about how to build a register form with database connection. For some reason storing the Hash Cookie in the browser and in the database doesn't work for me, even with the remember option include in the code and still it's like it doesn't do anything.
The remember option starts at 3:26:00 after that i did everything like he shows but at some point the Cookie hash doesn't show in my browser
I don't know what i'm doing wrong so maybe someone can point it out for me.
I know that the tutorial is outdated but in some way i like the way the guy explain what he is doing, i'm a noob at this but had to make the start at some point.
I had some problems whit the Hash::make function since PHP 7.2.2 works different this days, but i solved that in a different way as the tutorial shows and now i think i'm having problems whit the Hash.php file.
A other thing that i did was that i installed WORDPRESS a week a go and had to make some privileges changes in the database, could this be the reason why it's not working properly???, even the case that i'm not using the tables generated by WORDPRESS in the database but still working on the same table created by following the tutorial
This is the code on the Config.php file
<?php
class Config {
public static function get($path = null) {
if($path) {
$config = $GLOBALS['config'];
$path = explode('/', $path);
foreach($path as $bit) {
if(isset($config[$bit])) {
$config = $config[$bit];
}
}
return $config;
}
return false;
}
}
This is the code on Cookie.php file
<?php
class Cookie {
public static function exists($name) {
return (isset($_COOKIE[$name])) ? true : false;
}
public static function get($name) {
return $_COOKIE[$name];
}
public static function put($name, $value, $expiry) {
if(setcookie($name, $value, time() + $expiry, '/')) {
return true;
}
return false;
}
public static function delete($name) {
self::put($name, '', time() -1);
}
}
This is the code on DB.php file
<?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()) {
$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 = '';
$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 the code on the Hash.php file
<?php
class Hash {
public static function make($string, $salt = '') {
return hash('sha256', $string . $salt);
}
public static function salt($length) {
#return mcrypt_create_iv($length);
return substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", $length)), 0, $length);
}
public static function unique() {
return self::make(uniqid());
}
}
This is the code on the Input.php file
<?php
class Input {
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
} else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}
This is the code on the Redirect.php file
<?php
class Redirect {
public static function to($location = null) {
if($location) {
if(is_numeric($location)) {
switch($location) {
case 404:
header('HTTP/1.0 404 Not Found');
include 'includes/errors/404.php';
exit();
break;
}
}
header('Location:' . $location);
exit();
}
}
}
This is the code on the Session.php file
<?php
class Redirect {
public static function to($location = null) {
if($location) {
if(is_numeric($location)) {
switch($location) {
case 404:
header('HTTP/1.0 404 Not Found');
include 'includes/errors/404.php';
exit();
break;
}
}
header('Location:' . $location);
exit();
}
}
}
This is the code on the Token.php file
<?php
class Token {
public static function generate() {
return Session::put(Config::get('session/token_name'), md5(uniqid()));
}
public static function check($token) {
$tokenName = Config::get('session/token_name');
if(Session::exists($tokenName) && $token === Session::get($tokenName)) {
Session::delete($tokenName);
return true;
}
return false;
}
}
This is the code on the User.php file
<?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 create($fields = array()) {
if(!$this->_db->insert('users', $fields)) {
throw new Exception('There was a problem creating an account.');
}
}
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) {
$user = $this->find($username);
if($user) {
if($this->data()->password === Hash::make($password, $this->data()->salt)) {
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 logout() {
Session::delete($this->_sessionName);
}
public function data() {
return $this->_data;
}
public function isLoggedIn() {
return $this->_isLoggedIn;
}
}
This is the code on the Validate.php file
<?php
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = DB::getInstance();
}
Public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = trim($source[$item]);
$item = escape($item);
if($rule === 'required' && empty($value)) {
$this->addError("{$item} is required");
} else if(!empty($value)){
switch($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError("{$item} must be a minimun of {$rule_value} vcharacters.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError("{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$this->addError("{$rule_value} must match {$item}");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, '=', $value));
if($check->count()) {
$this->addError("{$item} already exists.");
}
break;
}
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($error) {
$this->_errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
This is the code on the init.php file
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'localhost',
'username' => '******',
'password' => '******',
'db' => 'users-pass'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
if(Cookie::exists(Config::get('remember/cookie_name')) && !Session::exists(Config::get('session/session_name'))) {
echo 'User asked to be remembered';
}
This is the code on the sanitize.php file
<?php
function escape($string){
return htmlentities($string, ENT_QUOTES, 'UTF-8');
}
This is the code on the index.php file
<?php
require_once 'core/init.php';
if(Session::exists('home')) {
echo '<p>' . Session::flash('home') . '</p>';
}
$user = new User();
if($user->isLoggedIn()) {
?>
<p>Hello <?php echo escape($user->data()->username); ?>!</p>
<ul>
<li>Log out</li>
</ul>
<?php
} else {
echo '<p>You need to log in or register</p>';
}
This is the code on login.php file
<?php
require_once 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remeber') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('index.php');
} else {
echo '<p>Sorry, logging in failed.</p>';
}
} else {
foreach ($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" id="password" autocomplete="off">
</div>
<div class="field">
<label for="remember">
<input type="checkbox" name="remember" id="remember"> Remember me
</label>
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Log in">
</form>
This is the code on logout.php file
<?php
require_once 'core/init.php';
$user = new User();
$user->logout();
Redirect::to('index.php');
This is the code on register.php file
<?php
require_once 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
)
));
if($validation->passed()) {
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'name' => Input::get('name'),
'joined'=> date('Y-m-d H:i:s'),
'group' => 1
));
Session::flash('home', 'You have been registered and can now log in!');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
</div>
<div class="field">
<label for="password">Choose a password</label>
<input type="password" name="password" id="password">
</div>
<div class="field">
<label for="password_again">Enter your password again</label>
<input type="password" name="password_again" id="password_again">
</div>
<div class="field">
<label for="name">Enter your name</label>
<input type="text" name="name" value="<?php echo escape(Input::get('name')); ?>" id="name">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Register">
</form>
Any help?
I was missing a (m) in the code on the login.php file
$remember = (Input::get('**remeber**') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
solved by changing it to:
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
Thanks anyway.
Related
guys first of all all this code here is a fork from codecourse tutorials in youtube! the thing is that in ubuntu 14.04 its running like a charm with no problems but when i try to use this in ubuntu 16.04 i get error in register function and i dont know how i can fix this!!
first of all in ubuntu 14.04 i used php (5.5-5.6) im not sure, mysql is 5.6 instead of ubuntu 16.4 that i use php 7 and mysql 5.7!
the error that im getting is this:
Exception: Sorry, there was a problem creating your account; in
/var/www/html/classes/User.php:35 Stack trace: #0
/var/www/html/register.php(47): User->create(Array) #1 {main}
thanks in advance you guys!!! if you need another script tell me to reply it!!
DB.php (database 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;
}
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;
}
}
user.php (user class)
class User {
private $_db,
$_data,
$_sessionName,
$_cookieName,
$isLoggedIn;
public function __construct($user = null) {
$this->_db = DB::getInstance();
$this->_sessionName = Config::get('sessions/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 {
//Logout
}
}
} else {
$this->find($user);
}
}
public function create($fields = array()) {
if(!$this->_db->insert('users', $fields)) {
throw new Exception('Sorry, there was a problem creating your account;');
}
}
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 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)) {
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);
return !empty($permissions[$key]);
}
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;
}
}
register.php (register script)
require_once 'core/init.php';
if (Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'name' => array(
'name' => 'Name',
'required' => true,
'min' => 2,
'max' => 50
),
'username' => array(
'name' => 'Username',
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'name' => 'Password',
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
));
if ($validate->passed()) {
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'name' => Input::get('name'),
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'joined' => date('Y-m-d H:i:s'),
'group' => 1
));
Session::flash('home', 'Welcome ' . Input::get('username') . '! Your account has been registered. You may now log in.');
Redirect::to('index.php');
} catch(Exception $e) {
echo $e, '<br>';
}
} else {
foreach ($validate->errors() as $error) {
echo $error . "<br>";
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="name">Name</label>
<input type="text" name="name" value="<?php echo escape(Input::get('name')); ?>" id="name">
</div>
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>">
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<div class="field">
<label for="password_again">Password Again</label>
<input type="password" name="password_again" id="password_again" value="">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Register">
</form>
init.php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.1.1',
'username' => 'root',
'password' => '123456',
'db' => 'db'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'sessions' => array(
'session_name' => 'user',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
if(Cookie::exists(Config::get('remember/cookie_name')) && !Session::exists(Config::get('sessions/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_session', array('hash', '=', $hash));
if($hashCheck->count()) {
$user = new User($hashCheck->first()->user_id);
$user->login();
}
}
Im new with PHP and im doing the OOP Login/Registers tutorials for a minor course so it not for a website that ill put on the www. And after an hour or 15 im stuck on a piece of code that doesn't seem to work. I've tried to solve it with a friend of mine who has more knowledge of PHP and I searched google, checked multiple forums and all the YouTube comments for a solution but im stuck. I know all the other code is correct because it all worked fine up to this:
so my qeustion is: what is the correct PHP code to make the unique case work.
case 'unique'
$check =$this->_db->get($rule_value,array($item,"=",
$value));
line 40> if($check->count()){
$this->addError("{$item} bestaat al.");
with this error:
! ) Fatal error: Call to a member function count() on a non-object in C:\wamp\www\websitegroop\classes\validate.php on line 40 Call Stack
validate class:
class Validate {
private $_passed = false,
$_errors = array(),
$_db = null;
public function __construct() {
$this->_db = Database::getInstance();
}
public function check($source, $items = array()) {
foreach($items as $item => $rules) {
foreach($rules as $rule => $rule_value) {
$value = trim($source[$item]);
if($rule === 'required' && empty($value)) {
$this->addError("{$item} is required");
} else if(!empty($value)) {
switch($rule) {
case 'min':
if(strlen($value) < $rule_value) {
$this->addError("{$item} moet minimaal {$rule_value} letters of cijfers zijn.");
}
break;
case 'max':
if(strlen($value) > $rule_value) {
$this->addError("{$item} kan maximaal {$rule_value} letters of cijfers zijn.");
}
break;
case 'matches':
if($value != $source[$rule_value]) {
$this->addError("{$rule_value} moet hetzelfde zijn als {$item}.");
}
break;
case 'unique':
$check = $this->_db->get($rule_value, array($item, "=", $value));
if($check->count()){
$this->addError("{$item} bestaat al.");
}
break;
}
}
}
}
if(empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($error) {
$this->_errors[] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
register.php:
<?php
require_once 'core/init.php';
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'gebruikersnaam' => array(
'required' => true,
'min' => 3,
'max' => 30,
'unique' => 'groopklanten'
),
'paswoord' => array(
'required' => true,
'min' => 6,
),
'paswoord_nogmaals' => array(
'required' => true,
'matches' => 'paswoord'
),
'bedrijfsnaam' => array(
'required' => true,
'min' => 3,
'max' => 30,
),
'kvknr' => array(
'required' => true,
'min' => 8,
'max' => 8,
'unique' => 'groopklanten'
),
'contactpersoon' => array(
'required' => true,
'min' => 4,
'max' => 30,
),
'functie' => array(
'required' => true,
'min' => 4,
'max' =>30,
),
'telbedrijf' => array(
'required' => true,
'min' => 10,
'max' => 12,
'unique' => 'groopklanten'
),
'adres' => array(
'required' => true,
'min' => 4,
'max' => 40,
'unique' => 'groopklanten'
),
'afleveradres' => array(
'min' => 4,
'max' => 40,
),
'postcode' => array(
'required' => true,
'min' => 6,
'max' => 7,
),
'woonplaats' => array(
'required' => true,
'min' => 3,
'max' => 30,
),
'emailadres' => array(
'required' => true,
'min' => 5,
'max' => 30,
'unique' => 'groopklanten'
)
));
if($validate->passed()) {
echo 'geregistreerd';
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="gebruikersnaam">Gebruikersnaam:</label>
<input type="text" name="gebruikersnaam" id="gebruikersnaam">
</div>
<div class="field">
<label for="paswoord">Kies een paswoord:</label>
<input type="password" name="paswoord" id="paswoord">
</div>
<div class="field">
<label for="paswoord_nogmaals">Nogmaals uw paswoord:</label>
<input type="password" name="paswoord_nogmaals" id="paswoord_nogmaals">
</div>
<div class="field">
<label for="bedrijfsnaam">Bedrijfsnaam:</label>
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam">
</div>
<div class="field">
<label for="kvknr">KvK nummer:</label>
<input type="text" name="kvknr" id="kvknr">
</div>
<div class="field">
<label for="contactpersoon">Naam contactpersoon:</label>
<input type="text" name="contactpersoon" id="contactpersoon">
</div>
<div class="field">
<label for="functie">Functie:</label>
<input type="text" name="functie" id="functie">
</div>
<div class="field">
<label for="telbedrijf">Telefoonnummer bedrijf:</label>
<input type="tell" name="telbedrijf" id="telbedrijf">
</div>
<div class="field">
<label for="adres">Adres:</label>
<input type="text" name="adres" id="adres">
</div>
<div class="field">
<label for="afleveradres"> Afwijkend aflever adres:</label>
<input type="text" name="afleveradres" id="afleveradres">
</div>
<div class="field">
<label for="postcode">Postcode:</label>
<input type="text" name="postcode" id="postcode">
</div>
<div class="field">
<label for="woonplaats">Woonplaats:</label>
<input type="text" name="woonplaats" id="woonplaats">
</div>
<div class="field">
<label for="emailadres">E-mail adres:</label>
<input type="email" name="emailadres" id="emailadres">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type ="submit" value="Register">
<input type="reset" name="reset" value="Reset Velden">
<p> Bij het verzenden gaat u automatisch akoord met de algemene voorwaarden!</p>
input class:
<?php
class input {
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
} else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}
Database class:
<?php
class Database {
private static $_instance = null;
private $_pdo,
$_qeury,
$_error = false,
$_result,
$_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 Database();
}
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} {value} ?";
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()) {
if(count($fields)) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO groopklanten (`" . 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;
}
}
init.php
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'localhost',
'username' => 'nick16061983',
'password' => 'N1sn0p1!A',
'db' => 'websitegroop'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'groopklanten',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' .$class. '.php';
});
All the other things i've tried so far show me that I always can register an existing username, or it will always say it is already registered. When the username is not in my database.
Thanks in advance,
Nick
Fatal error: Call to a member function count() on a non-object in C:\wamp\www\websitegroop\classes\validate.php on line 40 Call Stack
That's because the action() method returns false instead of current object, which means your query has failed to execute. There are two major reasons for this:
First, look at the following code snippet. There's a small syntax error here,
class Database {
private static $_instance = null;
private $_pdo,
$_qeury, // syntax error
...
It should be,
class Database {
private static $_instance = null;
private $_pdo,
$_query,
...
Second, your statement $sql = "{$action} FROM {$table} WHERE {$field} {$operator} {value} ?"; inside action() method is wrong, it should be like this:
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
So your entire Database class should be like this:
<?php
class Database {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_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 Database();
}
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()) {
if(count($fields)) {
$keys = array_keys($fields);
$values = null;
$x = 1;
foreach($fields as $field) {
$values .= '?';
if ($x < count($fields)) {
$values .= ', ';
}
$x++;
}
$sql = "INSERT INTO groopklanten (`" . 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;
}
}
?>
The reason you are getting this error is because the return value of your action() method on failure is a boolean. So if you attempt to call count() on a boolean (which is nonsense, because booleans cannot have methods), it's going to throw that error. Instead, you should check if the return value is even an object first, like so:
if ($check) { ... }
So long as $check is an object, it should pass this if statement. Then you can proceed as normal.
Here is something you can try:
// Make sure it's not false
if ($check) {
// Then count the errors
if ($check->count()) { ... }
}
Random note:
if ($check && $check->count()) { ... }
This code could also work if PHP doesn't check the second argument of the && operator if the first argument equates to false. Just a random note to save lines.
I'm following PHP Academy OOP Login/Register Tutorial currently in 16th part.
I used this code to create object in $data.
$data = $this->_db->get('users', array($field, '=', $user));
Then this code to add values from that object.
$this->_data = $data;
and trying to access the variables there by
public function data(){
return $this->_data;
}
$this->data()->password
The last code is throwing error. I tried to debug using this code
$vars = get_object_vars ($this->_data);
print_r($vars);
That is printing this line
Array ( [error] => [_requests] => Array ( [0] => stdClass Object ( [uid] => 16 [username] => admin [password] => 46651b6f1d743345d82d32da2cda7f891016ebe9f8b4416314b127e35b72fc30 [salt] => ²ê$ÓÕBF49ð®}€Æ¥A];ÛAc«íÊùÍ„s [name] => admin [joined] => 2015-03-17 22:53:52 [groups] => 1 ) ) )
What does this mean? How can I access those fields?
Here is the full code:
DB.php
<?php
/**
* Connect to database.
*
*/
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->_requests = $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())
{
if(count($fields))
{
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach ($fields as $field) {
$values .= '?';
if($x < count($fields))
{
$values .= ', ';
}
$x++;
}
// die($values);
$sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";
echo $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 uid = {$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;
}
}
user.php
<?php
class User{
private $_db,
$_data;
public function __construct($user = null)
{
$this->_db = DB::getInstance();
}
public function create($fields = array())
{
if(!$this->_db->insert('users', $fields))
{
throw new Exception("Problem Creating User Account");
}
}
public function find($user = null)
{
if($user)
{
$field = (is_numeric($user)) ? 'uid' : 'username';
$data = $this->_db->get('users', array($field, '=', $user));
if($data->count())
{
$this->_data = $data;
$vars = get_object_vars ($this->_data);
print_r($vars);
return true;
}
}
}
public function login($username = null, $password = null)
{
$user = $this->find($username);
if($user)
{
if($this->data()->password === Hash::make($password, $this->_data->salt))
{
echo "ok";
}
}
return false;
}
public function data()
{
return $this->_data;
}
}
login.php
<?php
require_once 'core/init.php';
if(Input::exists())
{
if(Token::check(Input::get('token')))
{
$validate = new Validation();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true
),
'password' => array(
'required' => true
),
));
if($validation->passed())
{
$user = new User();
$login = $user->login(Input::get('username'), Input::get('password'));
if($login)
{
echo "Success";
}
else{
echo "sorry! Failed";
}
}
else{
foreach ($validation->errors() as $error) {
echo $error, '<br />';
}
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username</label>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div class="field">
<label for="password">Password</label>
<input type="password" name="password" id="password" autocomplete="off">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Log In">
</form>
The variable returns array output. So you need to get values like $this->_data[0]->password, $this->_data[0]->username. Or when you store value to $this->_data, you can store the first child of the array.
instead of
$this->_data = $data;
You can use
$this->_data = $data->first();
So now you can get fields like $this->_data->username,$this->_data->password
I'm following PHPAcademy's OOP Login/register Tutorial. I'm in currently in 15th video of the series. ( https://www.youtube.com/watch?v=G3hkHIoDi6M&list=PLfdtiltiRHWF5Rhuk7k4UAU1_yLAZzhWc&index=15 )
When I register user, it's throwing exception. Everything seems fine. I checked YouTube comments and other websites but nothing is working for me to troubleshoot this.
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())
{
$this->_requests = $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())
{
if(count($fields))
{
$keys = array_keys($fields);
$values = '';
$x = 1;
foreach ($fields as $field) {
$values .= '?';
if($x < count($fields))
{
$values .= ', ';
}
$x++;
}
// die($values);
$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 uid = {$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;
}
}
User.php
<?php
class User{
private $_db;
public function __construct($user = null)
{
$this->_db = DB::getInstance();
}
public function create($fields = array())
{
if(!$this->_db->insert('users', $fields))
{
throw new Exception('Problem creating user account');
}
}
}
Hash.php
<?php
class Hash {
public static function make($string, $salt = '')
{
return hash('sha256', $string . $salt);
}
public static function salt($length)
{
return utf8_encode(mcrypt_create_iv($length));
}
public static function unique()
{
return self::make(uniqid());
}
}
Register.php
<?php
require 'core/init.php';
if(Input::exists()){
if(Token::check(Input::get('token')) )
{
$validate = new Validation();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'password_again' => array(
'required' => true,
'matches' => 'password'
),
'name' => array(
'required' => true,
'min' => 2,
'max' => 50
)
));
if($validate->passed()){
$user = new User();
$salt = Hash::salt(32);
try{
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt,
'name' => Input::get('name'),
'joined' => date('Y-m-d H:i:s'),
'group' => 1
)
);
} catch(Exception $e) {
die($e->getMessage());
}
}
else{
foreach ($validate->errors() as $error) {
echo $error . '<br />';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
</head>
<body>
<form action="" method="POST">
<div class="field">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
</div>
<div class="field">
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<div class="field">
<label for="password_again">Repeat Password:</label>
<input type="password" name="password_again" id="password_again">
</div>
<div class="field">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="<?php echo escape(Input::get('name')); ?>">
</div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="Register me">
</form>
</body>
</html>
Input.php
<?php
class Input {
public static function exists($type = 'POST')
{
switch ($type) {
case 'POST':
return (!empty($_POST)) ? true : false;
break;
case 'get':
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item)
{
if(isset($_POST[$item]))
{
return $_POST[$item];
}
elseif (isset($_GET[$item])) {
return $_POST[$item];
}
return '';
}
}
When I fill up the form wrongly, it shows the validation errors. When I fill up correctly, it says "Problem creating user account" as specified in User.php file.
Make the following temporary change to the query() method, to see what the problem is. It looks like a query error:
if($this->_query->execute())
{
$this->_requests = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else
{
$this->_error = true;
print_r($this->_query->errorInfo()); // New code line 1
exit(); // New code line 2
}
Then let us know what it says.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am learning PHP OOP by utilizing a PHP Academy tutorial. The tutorial is a Registration/Login system. I am having trouble on the "Remember Me" portion of the tutorial. This part of the tutorial retains a users selection to be able to stay logged in.
I am having an error:
"Fatal error: Call to a member function count() on a non-object in C:\xampp\htdocs\Rikarsen.hol.es\core\init.php on line 32
I have placed the PHP classes below to show what I have done thus far. Since I am new to PHP coding I am unable to locate the problem. Can anyone please help me? If any additional code is needed please let me know so I can supply it to you in order to help you discover my problem.
init.php
<?php
session_start();
$GLOBALS ['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'rikars'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 604800
),
'session' => array(
'session_name' => 'user',
'token_name' => 'token'
)
);
spl_autoload_register(function($class) {
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));
if($hashCheck->count()) {
echo 'asass';
}
}
I think I made a mistake in DB.php
<?php
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_result,
$_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;
}
public function ins() {
$instance = DB::getInstance();
$instance->get('users',array('user_id','=','1'));
if (!$instance->Count()) {
echo 'No user';
} else {
echo 'User exists';
}
}
}
?>
Your method action return false but you expect object.
if(Cookie::exists(Config::get('remember/cookie_name')) && Session::exists(Config::get('session/session_name'))) {
$hash = Cookie::get(Config::get('remember/cookie_name'));
$hashCheck = DB::getInstance()->get('users_sessions', array('hash', '=', $hash));
if($hashCheck === false) {
echo 'Action return false';
} else {
$count = $hashCheck->count();
if($count) {
echo 'Its object and count ='.$count;
}
}
}
Make sure your table name and column names are correct in get method. I was having the same problem and this was the solution that worked for me.