fetch(PDO::FETCH_OBJ not working

I’ve been trying to learn PDO and creating a login page this is what I have so far.

But I’m having a problem associating the data entered by the user with the data in the database.

Thank you in advance !

I have noticed that the problem occurs in this line while($row=$stmt->fetch(PDO::FETCH_OBJ)) any ideas on how to fix it ?

try {
   		
		$stmt = $pdo->query("SELECT COUNT(*) FROM account_info where a_username=':s'");
		
		$rows = $stmt->fetchColumn();
		$num_rows = count($rows);
			
	if ($num_rows>0)	
	    {
			$UserID=0;
			
			 	while($row=$stmt->fetch(PDO::FETCH_OBJ))
				{
				 // Assign each row of data to associative array
						  $UserID=$row["acc_id"];
						  
						  echo ('dddd');
				}
			  
			$myobj=array();
			array_push($myobj,array('isloggedin'=>'true','userid'=>$UserID));
			echo json_encode($myobj); 
			
		}

	else
	    {
		   $myobj=array();
		   array_push($myobj,array('isloggedin'=>'false'));
		   echo json_encode($myobj);
	    }

}
catch(PDOException $e)
{
  echo $e->getMessage();
}

This cannot be fixed. Despite the fact that your query is invalid (parameters ain’t escaped) and array access does not work on regular objects, you have no data to fetch after the fetchColumn() call, since you can only have one result set (due to COUNT()).

Adding onto this. stmt is prepared statement specific. Not specifically your $stmt variable, but the procedure that follows it. You’re calling for ->fetch() which is only for prepared statements.

http://php.net/manual/en/pdostatement.fetch.php


#NOTE
Apparently, you could use ->fetch() on non-prepared queries.


Moreover, the logic is flawed. Counting the number of rows makes no sense if your logic before hand is to check if the data exist. And the place holder named parameter cannot contain single quotes (').

This is why login systems should not be touched or mentioned about if you are a beginner. People fail to see that it takes more than just syntax knowledge. Even if you know a lot of PHP, the logic behind it all and the security of it is what matters.

Actually … no. Both a query and a prepared statement are expressed by PDO through the same PDOStatement class with all its fetch methods.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.