php fatal uncaught error problem

Jangga

Junior Member
Joined
Aug 8, 2016
Messages
196
Reaction score
11
Please guys, I have tried several thoughts in my head on how to bypass this error but it has been futile. The error I'm having is this:

Fatal error: Uncaught Error: Call to a member function passed() on boolean in C:\xampp\htdocs\test\crib\register.php:42 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test\crib\register.php on line 42

i simply dont know why the passed function has this problem. It seems okay. I really need yoour help guys..... please

the full code are shown below:

register.php
Code:
<?php

require_once '../core/init.php';
include 'header.php';

if(Input::exists('post')){
    if(Token::check(Input::get('token'))){
            $validate = new Validate();
            $validation = $validate->check($_POST, array(
                'fname'  => array(
                    'required'  =>  true,
                    'min'  =>  5,
                    'max'  => 20
                ),
                 'mname'  => array(
                    'required'  =>  false,
                    'min'  =>  5,
                    'max'  => 20
                ),
                 'lname'  => array(
                    'required'  =>  true,
                    'min'  =>  5,
                    'max'  => 20
                ),
                 'email'  => array(
                    'required'  =>  true,
                    'min'  =>  10,
                    'max'  => 20
                ),
                'password'  => array(
                    'required'  =>  true,
                    'min'  =>  5
                )
            ));
           
         if($validation->passed()) {
             $user = new User();
             $salt = Hash::salt(32);
             
             try {
                 $user -> create(array(
                     'firstname' => Input::get('fname'),
                     'middlename' => Input::get('mname'),
                     'lastname' => Input::get('lname'),
                      'email' => Input::get('email'),
                       'gender' => Input::get('sex'),
                     'phone' => Input::get('phone'),
                     'password' => Hash::make(Input::get('password'), $salt),
                      'salt' => $salt
                 ) );
                 
             } catch (Exception $e) {
                 die($e->getMessage());

             }
             
         } else {
             foreach ($validation->errors() as $error) {
                 echo $error, '<br>';
             }
         }  
}
}

?>

   
    <div class="container-fluid">           
        <nav class = "navbar navbar-default">
            <div class = "navbar-header">
                <button type = "button" class = "navbar-toggle"  data-toggle = "collapse" data-target = "#example-navbar-collapse">
                    <span class = "sr-only">Toggle navigation</span>
                    <span class = "icon-bar"></span>
                    <span class = "icon-bar"></span>
                    <span class = "icon-bar"></span>
                </button>
<!--                <a class = "navbar-brand navbar-left" href = "#">MySchooleyes</a>-->
            </div>
   
                <div class = "collapse navbar-collapse" id = "example-navbar-collapse">
                   <ul class = "nav navbar-nav">
                      <li class = "active"><a href = "#">HOME</a></li>
                      <li><a href = "about.php">ABOUT</a></li>
                      <li><a href = "#">BLOG</a></li>
                      <li><a href = "#">FAQs</a></li>
                      <li><a href = "contact.php">CONTACT</a></li>
                      <li class = "dropdown visible-xs">
                         <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown">
                            Access
                            <b class = "caret"></b>
                         </a>
                         <ul class = "dropdown-menu">
                            <li class = "divider"></li>
                            <li><a href = "#">Login</a></li>
                            <li><a href = "register.php">Sign up</a></li>
                         </ul>
                      </li>       
                   </ul>
                    </div>  
                     </nav>
    </div>
         
<div class="container">
 <div class="col-sm-10">
<form class="form-horizontal" action="" method="post">
    <div class="login-wrap">

        <div class="form-group">
            <label for="fname" class="control-label col-sm-2">Firstname</label>
       <div class="input-icon right col-sm-10"><input type="text" placeholder="Firstname" name="fname" value="<?php echo Input::get('fname');?>" class="form-control"></div>
        </div>
       <div class="form-group">
           <label for="mname" class="control-label col-sm-2">Middle name</label>
        <div class="input-icon right col-sm-10"><input type="text" placeholder="Middle name" name="mname" value="<?php echo Input::get('mname');?>" class="form-control" ></div>
       </div>
        <div class="form-group">
           <label for="lname" class="control-label col-sm-2">Last name</label>
           <div class="input-icon right col-sm-10"><input type="text" placeholder="Last name" name="lname" value="<?php echo Input::get('lname');?>" class="form-control"></div>
       </div>
       <div class="form-group">
           <label for="password" class="control-label col-sm-2">Password</label>
        <div class="input-icon right col-sm-10"><input type="password" placeholder="Password" name="password" class="form-control"></div>
        </div>
        <div class="form-group">
            <label for="email" class="control-label col-sm-2">Email</label>
        <div class="input-icon right col-sm-10"><input type="text" placeholder="Email" name="email" value="<?php echo Input::get('email');?>" class="form-control"></div>
        </div>
        <div class="form-group">
             <label for="sex" class="control-label col-sm-2">Gender</label>
             <div class="input-icon right col-sm-10">
            <label for="firstname" class="radio-inline">
                <input type="radio"  name="sex" value="m" > Male</label>
            <label for="firstname" class="radio-inline">
                <input type="radio"  name="sex" value="f" > Female</label></div>
        </div>
        <div class="form-group">
            <label for="phone" class="control-label col-sm-2">Phone</label>
        <div class="input-icon right col-sm-10"><input type="text" placeholder="Phone" name="phone" value="<?php echo Input::get('phone');?>" class="form-control" ></div>
        </div>
        <div class="form-group checkbox">
            <div class="input-icon col-xs-offset-3"><input type="checkbox"  value="remember"> Keep me logged in</div>
        </div>
    <input type="hidden"  name="token" value="<?php echo Token::generate();?>">
    <br><br>
     <div class="form-group">
            <button type="submit" class="btn btn-warning col-xs-offset-2">Register<i class="fa fa-chevron-circle-right"></i></button>
        </div>
    </div>
</form>
</div>
</div>

   <?php include 'footer.php';
[/B]

validate.php
Code:
<?php

class Validate {
    //defining variables
    private $_passed  =  false,
               $_errors  = array(),
               $_db = null;
               
    //getting db instance since we will be using it
    public function __construct() {
        $this -> _db = DB::getInstance();
}
   
    //check the rules defined for a form
    public function check($source, $items = array()) {
        foreach ($items as $item => $rules) {
            foreach ($rules as $rule => $rule_value) {

                $value = trim($source[$item]);
                //$item should be escaped with the escape function
                $item = $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 minimum of {$rule_value} characters.");
                        }
                    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)){
        return $this->_passed = true;
        }
       
        return $this;
    }
   
    public function addError($error){
        $this->_errors[] = $error;
    }
   
     public function errors() {
     return $this->_errors;
    }
   
     public function passed() {
        return $this->_passed;
    }
   
   
}

[/B]
 
Unfortunately that's not enough info to tell the problem.
The error is with the passed function, which is a member of Validate, and the file containing that class is not visible to us.
 
Unfortunately that's not enough info to tell the problem.
The error is with the passed function, which is a member of Validate, and the file containing that class is not visible to us.
Thanks for replying..
It is visible. I pasted it. The function is inside validate class.....no where else
 
Wooow, I don't know how I did not see the second file, sorry.

I think the problem is maybe that in Validator around line 58 if $this->_errors is empty, you return $this->_passed = true; which is boolean true, so you cant call passed later on that.
I think removing return before $this->_passed = true; solves your problem.
 
Wooow, I don't know how I did not see the second file, sorry.

I think the problem is maybe that in Validator around line 58 if $this->_errors is empty, you return $this->_passed = true; which is boolean true, so you cant call passed later on that.
I think removing return before $this->_passed = true; solves your problem.
Thanks a bunch. It worked. How u able to detect it? Please teach me
 
if input exists ? do they, try and see if the form condition are set properly .

are you inputting the correct chareters in the form ?
 
if input exists ? do they, try and see if the form condition are set properly .

are you inputting the correct chareters in the form ?
Thanks man....issues resolved
 
lol ok.

did the database get the hash with salt always use md5 and salt more secure
 
Thanks a bunch. It worked. How u able to detect it? Please teach me
Well, it's not like "detecting", I've just read through your code line-by-line and understood what each line does.
If empty($this->_errors) was true you returned true in the check function, and code never reached line 62: return $this; which would return the validator itself.
So after that $validation become (bool)true value in register.php after line 35. you can't call passed anymore, because $validation is not an instance of Validate anymore, but a simple boolean value.
I hope you can understand what I wrote.
 
Well, it's not like "detecting", I've just read through your code line-by-line and understood what each line does.
If empty($this->_errors) was true you returned true in the check function, and code never reached line 62: return $this; which would return the validator itself.
So after that $validation become (bool)true value in register.php after line 35. you can't call passed anymore, because $validation is not an instance of Validate anymore, but a simple boolean value.
I hope you can understand what I wrote.

I'm having same error in another section of my coding. I'm trying to figure it out ... Why this bool issue with oop? This is my first project with oop
 
Post your code here, maybe I can help and then I'll try to explain it.
 
Post your code here, maybe I can help and then I'll try to explain it.


please friend here is it:

Fatal error: Uncaught Error: Call to a member function count() on boolean in C:\xampp\htdocs\myschooleyes\classes\User.php:74 Stack trace: #0 C:\xampp\htdocs\test\classes\User.php(90): User->find('jangga') #1 C:\xampp\htdocs\test\crib\login.php(25): User->login('jangga', 'jangga', false) #2 {main} thrown in C:\xampp\htdocs\test\classes\User.php on line 74


login
Code:
<?php

if(Input::exists('post')) {
    if(Token::check(Input::get('token'))) {
       
        $validate = new Validate();
        $validation = $validate ->check($_POST, array(
                'uname'  => array('required'  =>  true),
                'password'  => array('required'  =>  true),
        ));
       
        if($validation->passed()) {
            //log in user
            $user  =  new User();
           
            $remember  =  (Input::get('remember') === 'on')  ?  true  :  false;
            $login  =  $user->login(Input::get('uname'), Input::get('password'), $remember);
           
            if($login) {
               
             
                Redirect::to('dashboard.php');
               
            } else {
                echo 'sorry not logged in';
            }
        } else {
            foreach ($validation->errors() as $error) {
                echo $error, '<br>';   
            }
        }
       
    }
}

?>



        <div class="container-fluid">
        <div class="row breadcrumb">
        <div class="breadcrumb-item col-md-2 col-sm-4 col-xs-4"> No.1 Consultant</div>
        <div class="breadcrumb-item col-md-2 col-sm-4 col-xs-4">Certified </div>
        <div class="breadcrumb-item col-md-2 col-sm-4 col-xs-4"> Leading Service Provider</div>
        <div class="col-md-2 col-sm-4 hidden-xs"></div>
        <div class="breadcrumb-item col-md-2 col-sm-4 hidden-xs">Login</div>
        <div class="breadcrumb-item col-md-2 col-sm-4 hidden-xs"> Sign Up</div>
        </div>
      </div>
    <div class="container-fluid">           
        <nav class = "navbar navbar-default">
            <div class = "navbar-header">
                <button type = "button" class = "navbar-toggle"  data-toggle = "collapse" data-target = "#example-navbar-collapse">
                    <span class = "sr-only">Toggle navigation</span>
                    <span class = "icon-bar"></span>
                    <span class = "icon-bar"></span>
                    <span class = "icon-bar"></span>
                </button>
<!--                <a class = "navbar-brand navbar-left" href = "#">MySchooleyes</a>-->
            </div>
   
                <div class = "collapse navbar-collapse" id = "example-navbar-collapse">
                   <ul class = "nav navbar-nav">
                      <li class = "active"><a href = "#">HOME</a></li>
                      <li><a href = "about.php">ABOUT</a></li>
                      <li><a href = "#">BLOG</a></li>
                      <li><a href = "#">FAQs</a></li>
                      <li><a href = "contact.php">CONTACT</a></li>
                      <li class = "dropdown visible-xs">
                         <a href = "#" class = "dropdown-toggle" data-toggle = "dropdown">
                            Access
                            <b class = "caret"></b>
                         </a>
                         <ul class = "dropdown-menu">
                            <li class = "divider"></li>
                            <li><a href = "login.php">Login</a></li>
                            <li><a href = "register.php">Sign up</a></li>
                         </ul>
                      </li>       
                   </ul>
                    </div>  
                     </nav>
    </di
       
<div class="container">
 <div class="col-sm-10">
     <div class="login-logo">
          <img src="images/logo.png" width="150" alt=""/>
      </div>

      <h2 class="form-heading">Register</h2>
      <div class="container log-row">
<form class="form-horizontal" action="" method="post">
    <div class="login-wrap">

        <div class="form-group">
            <label for="uname" class="control-label col-sm-2">Username</label>
       <div class="input-icon right col-sm-10"><input type="text" placeholder="Username" name="uname" value="<?php echo Input::get('uname');?>" class="form-control"></div>
        </div>
       <div class="form-group">
           <label for="password" class="control-label col-sm-2">Password</label>
        <div class="input-icon right col-sm-10"><input type="password" placeholder="Password" name="password" class="form-control"></div>
        </div>
        <div class="form-group">
             <label for="group" class="control-label col-sm-2">Rights</label>
             <div class="input-icon right col-sm-10">
            <label for="Student" class="radio-inline">
                <input type="radio"  name="group" value="1" > Student</label>
            <label for="Mod" class="radio-inline">
                <input type="radio"  name="group" value="2" > Mod</label></div>
        </div>
       
        <div class="form-group checkbox">
            <div class="input-icon col-xs-offset-3"><input type="checkbox"  value="remember"> Keep me logged in</div>
        </div>
    <input type="hidden"  name="token" value="<?php echo Token::generate();?>">
    <br><br>
     <div class="form-group">
            <button type="submit" class="btn btn-warning col-xs-offset-2">Login<i class="fa fa-chevron-circle-right"></i></button>
        </div>
        <div class="form-group ">
       <a href='login' class="btn btn-success col-xs-offset-6">Register </a>
       </div>
    <br><br>
        <p>Lost Your Password? <a id="btn-register" href="recover">Reset Password</a></p>
    </div>
</form>
</div>
</div>
</div>

user class
Code:
<?php

class User{
    //put your code here
    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');
       
        //check if a user is logged in
        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('user', $fields)) {
            throw new Exception("There was a problem creating");
        }
       
    }
   
    public function find($user = null){
        if($user) {
            $field  =  (is_numeric($user)) ? 'id' : 'firstname';
            $data  = $this->_db->get('user', array($field, '=', $user));
           
            if($data->count()) {
                $this->_data  =  $data->first();
                die('good guy');
                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->_sesssionName, $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('user_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 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;
    }



}

db class
Code:
<?php


class DB {
    //put your code here
     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()) {
             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})";
                 
                 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;
        }
       
       
}
 
What I see is the problem some kind of similar to the previous.
In User class, find function, around line 74 you check if($data->count())
However before this line, you get the $data variable with $data = $this->_db->get('user', array($field, '=', $user));
Somehow this expression returns a boolean true or false. Maybe because the user is not found or there was an error.
And boolean variable is not an object you expect to have a ->count() function
Try debugging why $data becomes a boolean, var_dump the result of the SQL query.
 
What I see is the problem some kind of similar to the previous.
In User class, find function, around line 74 you check if($data->count())
However before this line, you get the $data variable with $data = $this->_db->get('user', array($field, '=', $user));
Somehow this expression returns a boolean true or false. Maybe because the user is not found or there was an error.
And boolean variable is not an object you expect to have a ->count() function
Try debugging why $data becomes a boolean, var_dump the result of the SQL query.

I have tried countless Times man... Yet to no avail. The funny thing is it seems okay. Oop is troublesome
 
As I inspected your code deeper, maybe the problem is in the DB class, action function around line 63, where you are checking if($this->query($sql, array($value))->error())
In this part, are you sure you want to return $this is there WAS an error? Didn't you forget an exclamation mark to check if error() returned false?
Because as I see, if there was an error, you return $this, if no error, you just return false at the end of the action function.
 
As I inspected your code deeper, maybe the problem is in the DB class, action function around line 63, where you are checking if($this->query($sql, array($value))->error())
In this part, are you sure you want to return $this is there WAS an error? Didn't you forget an exclamation mark to check if error() returned false?
Because as I see, if there was an error, you return $this, if no error, you just return false at the end of the action function.

I'll look into it now. That will obviously be my mistake. However, since I'm a bit new to oop PHP. I use return $this to enable chaining bit i don't quite understand the concept behind it. Honestly, can u direct an article for me on returning bools/$this? Mind chatting on telegram, WhatsApp, messenger?
 
Back
Top