I know a bit of php and starting to learn php oop and following a guide from alex at php academy how every when trying to insert into a db it doesn't seem to insert.
I have db detail set up like this
init.php
<?php
session_start();
$GLOBALS['config'] = array(
'mysql' => array(
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'db' => 'oop'
),
'remember' => array(
'cookie_name' => 'hash',
'cookie_expiry' => 2592000
),
'session' => array(
'session_name' => 'user'
)
);
spl_autoload_register(function($class){
require_once 'classes/' . $class . '.php';
});
require_once 'functions/sanitize.php';
?>
this is my database class every thing seems to work fine untill i get to public function insert
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->_result = $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];
$vaule = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if (!$this->query($sql, array($vaule))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
}
public function delete() {
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 users (`" . implode('`,`', $keys) . "`) VALUES ({$values})";
if(!$this->query($sql, $fields)->error()){
return true;
}
}
return false;
}
public function results(){
return $this->_result;
}
public function first() {
return $this->results()[0];
}
public function error() {
return $this->_error;
}
public function count() {
return $this->_count;
}
}
?>
and this is what I am using to submit to db
index.php
<?php
require_once 'core/init.php';
$user = db::getInstance()->insert('users', array(
'username' => 'pravaut',
'passowrd' => 'test',
'salt' => 'salt'
));
?>
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();
}
}
i'm using this methode to get data from db
class Database {
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 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 {$table} (`".implode('`,`', $keys)."`) VALUES({$values})";
if (!$this->query($sql, $fields)->error()) {
return true;
}
}
return false;
}
public function update($table, $id, $fields = array()) {
$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 what i want to get AND
this is my table
this is my code ...
public function getModule() {
$epreuve = $this->_db->get('epreuve', array('concour_code', '=', $this->data()->concour_code));
foreach($epreuve->results() as $epreuve){
echo "<tr><td>".$epreuve->designation."</td>"
.$module = $this->_db->get('module', array('epreuve_code', '=', $epreuve->code ));
foreach($module->results() as $module){
echo "<tr><td>".$epreuve->designation."</td>";
}
"</tr>";
}
}
but i have this error
'' Catchable fatal error: Object of class Database could not be converted to string ''
The error seems to be here:
echo "<tr><td>".$epreuve->designation."</td>"
.$module = $this->_db->get('module', array('epreuve_code', '=',
Note that you did not close echo with semi colon, and there is a dot before $module, so PHP is trying to string concat echo string with $module class plus the iteration also inside the concatenation. You cant do that.
Do the following:
public function getModule() {
$epreuve = $this->_db->get('epreuve', array('concour_code', '=', $this->data()->concour_code));
foreach($epreuve->results() as $epreuve){
echo "<tr>";
echo "<td>".$epreuve->designation."</td>";
$module = $this->_db->get('module', array('epreuve_code', '=', $epreuve->code ));
foreach($module->results() as $module){
echo "<td>".$epreuve->designation."</td>";
}
echo "</tr>";
}
}
Suggesiton:
On your code
foreach($epreuve->results() as $epreuve){
AND
foreach($module->results() as $module){
You should not use the same variable name of what you are iterating. Try change it to
public function getModule() {
$epreuve = $this->_db->get('epreuve', array('concour_code', '=', $this->data()->concour_code));
foreach($epreuve->results() as $epreu){
echo "<tr>";
echo "<td>".$epreu->designation."</td>";
$module = $this->_db->get('module', array('epreuve_code', '=', $epreu->code ));
foreach($module->results() as $mod){
echo "<td>".$epreu->designation."</td>";
}
echo "</tr>";
}
}
NOTE: The HTML table is a bit messy I tried by best to understand it. Change it to your needs.
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.