New fatal error just creeped in on me

I been working on a script since yesterday and I think all was well until I commented the Redirect::to index line after my script has gone through. I didn’t noticed any errors and all the data in my forms gets uploaded to mysql as it should.

What I just noticed by staying on the same page after the update is this message: the ( if($user->data()->group == 1) {) line

Fatal error: Call to a member function data() on boolean in C:\xampp\htdocs\database\includes\title.php on line 6

I tried removing the require_once title.php in my script and it removed the fatal error problem but also noticed that my form no longer completely refresh itself. it stops right after the first field which is a select tag for [siteid] and the option tag doesn’t reload the content that was populated by mysql prior to updating. When I first load the page everything is fine and it update correctly to all columns in my database. I been looking for an explanation but after so many hours looking at this I just can’t see why this is happening? any idea?

this is the script that causes the error:

<?php 
         if(Session::exists('home')){
            echo '<span class="flash">' . Session::flash('home') . '</span>';
            }
             // could say if user ! permission than redirect to another page
              if($user->data()->group == 1) {
                 echo '<br /><p class="title">User: &nbsp; <a  href="profile.php?user=' 
                 . escape($user->data()->id) . '">' . escape($user->data()->firstname) . ' ' . escape($user->data()->lastname) .'</a></p>';
                }else{
                     echo '<br /><p class="title" >Administrator:&nbsp;   <a class="title a" href="profile.php?user=' 
                     . escape($user->data()->id) . '">' . escape($user->data()->firstname) . ' ' . escape($user->data()->lastname) .'</a></p>';///changed email to ID in user->data()->id
                 }
                
         ?>

this is my html form:

<form action="" method="post" enctype="multipart/form-data" id="uploadImage">
                   
                 <div class="fluid stretch">  
                  <label for="FSSiteid" class="labelStretch">Where was the drill was performed? </label>
                   <br />
                     <select name="FSSiteid" required class="input" id="FSSiteid">
                     <option > Select a Site </option>
                     <?php 
                        $result_site = DB::getInstance()->query("SELECT id, site FROM sites");
                        if($result_site->count()){
							
                          foreach($result_site->results() as $row){
                             $selected = $row->id == $user->data()->FSSiteid ? ' selected="selected"' : null;?>
                      <option value="<?php echo $row->id ?>"<?php echo $selected?> ><?php echo $row->site ?></option>
                             <?php  
                           }
                         }
						 
                    ?>
                    </select>
                   
                    
                   </div> ...

That error says there is boolean value (true of false) in your $user variable, but you’re trying to use it as an object (calling $user->data()). Check where value for that variable come from.

yes I know??? it was working before without a problem. the value is not a bolean at all, print_r returns the content of the variable and it is not a boolean it is an object. I can actually call this object by itself with an echo statement and I get the right value returned. I just re-tested. whats weird is I don’t get this error message when I first load the page; the script that is giving problem is working fine. Only after I hit submit button on my form. the page won’t reload totally and I get this error boolean message

the only clue that I had that something wasn’t working properly is the Flash message I am supposed to get in my index.php file once the firesafety.php has sucessfully executed it’s script. When I look at my DB all fields were updated properly. I brought this Flash message into the firesafety.php file to check if it was set and it echos perfectly on the page, but won’t show when I redirect to index.php with the same session variable set in flash?

here is the validation and redirect to index script from firesafety.php

<?php require_once 'core/init.php';
$user = new User();

if(!$user->isLoggedIn()) {
		Redirect::to('index.php');
	}
	if(Input::exists()) {
		
		
		if(Token::check(Input::get('token'))) {
			
			$validate = new Validate();
			$validation = $validate->check($_POST, array(
				'FSSiteid' =>array(
					'required' => true,
				),
				'FSDate' =>array(
					'required' => true,
				),
				'action' =>array(
					'required' => true,
				),
				'prepByAssociateid' =>array(
					'required' => true,
				),
				'reviewedByAssociateid' =>array(
					'required' => true,
				)
				
			));
			
			if($validation->passed()) {
				
				try { 						
				$user=DB::getInstance()->insert('firesafety', array(//////I took the $user-> before DB::getINstance
						'FSSiteid' => Input::get('FSSiteid'),
						'FSDate' => Input::get('FSDate'),
						'FSTimeStart' => Input::get('FSTimeStart'),
						'FSTimeStop' => Input::get('FSTimeStop'),
						'action' => Input::get('action'),
						'deviceid' => Input::get('deviceid'),
						'locationid' => Input::get('locationid'),
						'staffPosted' => Input::get('staffPosted'),
						'elevatorLock' => Input::get('elevatorLock'),
						'DWClosed' => Input::get('DWClosed'),
						'corridorClear' => Input::get('corridorClear'),
						'powerOff' => Input::get('powerOff'),
						'bellLights' => Input::get('bellLights'),
						'procedureFollowed' => Input::get('procedureFollowed'),
						'residentPanic' => Input::get('residentPanic'),
						'prepByAssociateid' => Input::get('prepByAssociateid'),
						'reviewedByAssociateid' => Input::get('reviewedByAssociateid'),
						'drillDescription' => Input::get('drillDescription'),
						'followUp' => Input::get('followUp'),
						'FSComment' => Input::get('FSComment'),
					));
					Session::flash('home', '<<<----Your details have been updated----->>>.');
					//Redirect::to('index.php');
				} catch(Exception $e) {
					die($e->getMessage());
				}
			} else {
				foreach ($validation->errors() as $error) {
					echo $error, '</br>';
				}
			}
		}
		
	}

?>

You’re assigning $user the return value of insert(), which I’m guessing returns a boolean true or false to indicate success.

well I;m pretty sure that this is not the culprit.

I actually have another question on the board regarding this piggy, I;m new to PDO and was wondering about creating new instances I have tried to give that line a different variable name but when I do so the whole script stops working. When I var-dump $user I get all the instances that I created with DB::getInstance() method. The insert() method is the actual query to mysql. Everything from $user=DB::getInstance()->insert(… works ok

Where did you insert that print_r? Right above the problem line? Or somewhere else?

I’ve echoed $user->data()->group before and after the if statement and get the value 2 which is what I would expect.

<div id="main" class="fluid ">
      
      <div class="pageTitle">
     
	  <?php include ("includes/title.php");
	  echo $user->data()->group;////////////////////////// value returned = 2  which is the correct value in my database for this field and current user.
	  
	  ?>
    
      </div pageTitle>
    
    	  <form action="" method="post" enctype="multipart/form-data" id="uploadImage">
                   
                 <div class="fluid stretch">  
                  <label for="FSSiteid" class="labelStretch">Where was the drill was performed? </label>
                   <br />
                     <select name="FSSiteid" required class="input" id="FSSiteid">
                     <option > Select a Site </option>
                     <?php 
                        $result_site = DB::getInstance()->query("SELECT id, site FROM sites");
                        if($result_site->count()){
                           foreach($result_site->results() as $row){
                             $selected = $row->id == $user->data()->FSSiteid ? ' selected="selected"' : null;?>
                      <option value="<?php echo $row->id ?>"<?php echo $selected?> ><?php echo $row->site ?></option>
                             <?php  
                           }
                         }
                    ?>
                    </select>
                   </div>

Wait, you have an error on that line in script from your first post:

if($user->data()->group == 1) {

Can you dump $user right before that line?

var_dump($user);
if($user->data()->group == 1) {

Because now we want to prove there is boolean really and not the object when you get that error.

Hmmmmm strange I get it twice??? maybe that’s the problem? 2 instances of the same values

User Object
(
    [_db:User:private] => DB Object
        (
            [_pdo:DB:private] => PDO Object
                (
                )

            [_query:DB:private] => PDOStatement Object
                (
                    [queryString] => SELECT * FROM associates WHERE id = ?
                )

            [_error:DB:private] => 
            [_results:DB:private] => Array
                (
                    [0] => stdClass Object
                        (
                            [id] => 712
                            [active] => 0
                            [employerid] => 1
                            [jobid] => 1
                            [siteid] => 1
                            [firstname] => Alan
                            [lastname] => Des
                            [joined] => 2015-05-24 01:20:26
                            [group] => 2
                            [address] => 3rd Eve
                            [city] => sq
                            [province] => BC
                            [country] => Canada
                            [postalcode] => V8B 0S3
                            [phone] => 7782667666
                            [wphone] => 604 848 2777
                            [extphone] => 5006
                            [email] => alman@hotmail.com
                            [comment] => administrator of this site
                            [username] => 
                            [salt] => f����!�Jܩ�q�E��/���劘crY�Y
                            [password] => 160b72e40fc7009382f71d3435a4caec359576d0278260c912b4ef0fa2a4711d
                            [name] => 
                            [email_code] => e59efccf10414c8a54d2743d40246a00
                            [pic] => 712_alsuitsmblur.jpg
                        )

                )

            [_count:DB:private] => 1
        )

    [_data:User:private] => stdClass Object
        (
            [id] => 712
                            [active] => 0
                            [employerid] => 1
                            [jobid] => 1
                            [siteid] => 1
                            [firstname] => Alan
                            [lastname] => Des
                            [joined] => 2015-05-24 01:20:26
                            [group] => 2
                            [address] => 3rd Eve
                            [city] => sq
                            [province] => BC
                            [country] => Canada
                            [postalcode] => V8B 0S3
                            [phone] => 7782667666
                            [wphone] => 604 848 2777
                            [extphone] => 5006
                            [email] => alman@hotmail.com
                            [comment] => administrator of this site
                            [username] => 
                            [salt] => f����!�Jܩ�q�E��/���劘crY�Y
                            [password] => 160b72e40fc7009382f71d3435a4caec359576d0278260c912b4ef0fa2a4711d
                            [name] => 
                            [email_code] => e59efccf10414c8a54d2743d40246a00
                            [pic] => 712_alsuitsmblur.jpg
        )

    [_sessionName:User:private] => user
    [_cookieName:User:private] => hash
    [_isLoggedIn:User:private] => 1
)

and you get Fatal Error right after that dump?

Te more I think about it, the more I think it is my local server that is giving me grief. I’ve had this problem before.

So, I just got out of bed, made coffee and checked my page again and guest what? Now, it’s working ok without a fatal error and I didn’t do nothing! The only thing that is still not working is the flash message that I am passing from this page to my index page notifying me that the record was successfully updated.

What is even weirder, now it’s my Update Profile page that is screwing with me. When I try to update a record of a user the page returns an error saying that this email address already exist(I have set a rule throughout my site for email to be unique) but this shouldn’t matter since I am updating the user’s own current record???

When I had a similar problem about a week ago, I talked to someone who said I might be having a latent server problem. I guess my next question is, how do you check if your local server is getting lazy lol?

It’s entirely possible that when your script attempted to fill the $user variable, it failed, and thus $user was set to FALSE (the default return of many database functions that suffer an error).

This would then cause $user to be a boolean (FALSE), and $user->data() to generate the OP error.

You may want to check with your host about their database server stability.

thanks for checking in on me StarLion,

I am working with Xampp localhost and mysql

Show us your User class definition?

here is the user Class:

<?php
	class User {
		private $_db,
				$_data,
				$_sessionName,
				$_cookieName,
				$_isLoggedIn;
		
		
		public function __construct($user = null) {
			$this->_db = DB::getInstance();
			$this->_sessionName = Config::get('session/session_name');
			$this->_cookieName = Config::get('remember/cookie_name');
			if(!$user) {
				if(Session::exists($this->_sessionName)) {
					$user = Session::get($this->_sessionName);
					if($this->find($user)) {
						$this->_isLoggedIn = true;
					} else {
						// process logout
					}
				}
			} else {
				$this->find($user);
			}
		}
		
		
		public function update($fields = array(), $id = null) {
			if(!$id && $this->isLoggedIn()) {
				$id = $this->data()->id;
			}
			if(!$this->_db->update('associates', $id, $fields)) {
				throw new Exception('There was a problem updating.');
			}
		}
		
		
		
		public function create($fields = array()) {
			if(!$this->_db->insert('associates', $fields)) {
				throw new Exception('There was a problem creating your account.');
			}
		}
		
		
		
		public function find($user = null) {
			if($user){
				$field = (is_numeric($user)) ? 'id' : 'email';
				
				$data = $this->_db->get('associates', array($field, '=', $user));
				//echo '<pre>' . print_r($data, 1) . '</pre>';/////////////////////////////////////////////////////////////////////////////
				if($data->count()) {
					
					$this->_data = $data->first();
					return true;
				}
			}
			 
			return false;
		}
		
		
		
		public function login($email = null, $password = null, $remember = false) {
			
			if(!$email && !$password && $this->exists()) {
				Session::put($this->_sessionName, $this->data()->id);
			} else {
				$user = $this->find($email);
				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 check($fields = array()) {
			if(!$this->_db->get('associates', $fields)) {
				throw new Exception('There was a problem logging into your account.');
			}
		}
		
		
		public function email($to, $subject, $body) {
			if(!mail($to, $subject, $body, "From: almanages@hotmail.com")) {////added a "not" in front of mail
				throw new Exception('There was a problem sending your activation email. So your account cannot be created at this time.');
			}
			return true;
		}
		
		
		
		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 hasPermission() {
			$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
			//print_r($group->first());
			if($group->count()) {
				print_r( $group);
				//$permissions = json_decode($group->first()->permissions);
				
				//var_dump($permissions);
			//	if($permissions[$key] == true) {
			//	return true;
			//	}
			}
		//	return false;
		}
		
	
		public function data() {
			return $this->_data;
		}
		
		
		public function isLoggedIn() {
			return $this->_isLoggedIn;
		}
	}
?>

here is the DB Class

<?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;
		}
		
		
		
		private function action($action, $table, $where = array()) {
			if(count($where) === 3) {
				$operators = array('=', '>', '<', '>=', '<=');
				$field 		= $where[0];
				$operator 	= $where[1];
				$value 		= $where[2];
				
				if(in_array($operator, $operators)) {
					$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
					
					if(!$this->query($sql, array($value))->error()) {
						return $this;
					}
				}
			}
			return false;
		}
		
		
		//// this function is a shorth cut of the action function.
		public function get($table, $where) {
			return $this->action('SELECT *', $table, $where);
		}
		
		
		
		public function check($table, $fields = array()) {
			$where = array();
			foreach($fields as $item => $value) {
				//$sql .= "SELECT * FROM {$table} WHERE {$item} = {$value};"
				array_push($where, array($item, '=', $value));
			}
			$operators = array('=', '>', '<', '>=', '<=');
				$field 		= $where[0][0];
				$operator 	= $where[0][1];
				$value 		= $where[0][2];
				if(in_array($operator, $operators)) {
					$sql = "SELECT * FROM {$table} WHERE {$field} {$operator} ?";
					
					if(!$this->query($sql, array($value))->error()) {
						return $this->_results;
					}
				}
				return false;
		}
		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 => $values) {
				$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;
		}
	}
?>

User::find() has the possibility of returning FALSE and your constructor doesnt check for this state…might want to catch that in the find function (finding no data should be an error!)

public function find($user = null) {
			if($user){
				$field = (is_numeric($user)) ? 'id' : 'email';
				
				$data = $this-&gt;_db-&gt;get('associates', array($field, '=', $user));
				//echo '&lt;pre&gt;' . print_r($data, 1) . '&lt;/pre&gt;';/////////////////////////////////////////////////////////////////////////////
				if($data-&gt;count()) {
					
					$this-&gt;_data = $data-&gt;first();
					return true;
				}
                               //If you get to this point, something has gone wrong!!!!
			}
			 
			return false;
		}

Incidentally, this will also fail if user’s ID = 0, or email = “0” or “” (because then something gets passed into $user that evaluates as FALSE for purposes of IF)

also, your exception throws arnt caught by anything, so will cause fatal errors if they trigger.