2

In this code fetch(PDO::FETCH_ASSOC) retunrs false even if $row>0.
I couldn't find why this is happening.

Here session is not set as $member is null.

<?php 

$sql = "SELECT * FROM members WHERE username=:decrypted_login and password=:decrypted_pass";

$result = $dbh->prepare($sql);
$result->bindParam(':decrypted_login', $decrypted_login);
$result->bindParam(':decrypted_pass', $decrypted_pass);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);

if($rows > 0)
{
  $member = $result->fetch(PDO::FETCH_ASSOC);
  session_regenerate_id();
  $_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
  $_SESSION['SESS_PASSWORD'] = $member['password'];
  $_SESSION['SESS_FIRST_NAME'] = $member['firstname'];
  session_write_close();
}

?>

I've read many and stackoverflow questions and forums but couldn't find a solution for this.

var_dump($row); // gives an array   

var_dump($member) //shows bool(false).  
Jonas
  • 121,568
  • 97
  • 310
  • 388
Shyam3089
  • 459
  • 1
  • 5
  • 20
  • You are looking for a matching user and expect two results but only the second one seems to be relevant for you... but you don't have an `ORDER BY` clause so you'd choose one arbitrarily if you actually had two. – Álvaro González Jul 26 '14 at 10:38

1 Answers1

2

You are using fetch instead of rowCount:

$rows = $result->rowCount();

From PDO::fetch():

Fetches the next row from a result set.

The return value of this function on success depends on the fetch type. In all cases, FALSE is returned on failure.

I'd assume here that only 1 user can exist in the database with those credentials, when you first execute the $rows = $result->fetch(PDO::FETCH_NUM);, the resultset cursor is moved over to the next row-set (which doesn't exist, as there was only a single row).

Therefore, you get a false in the later call.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • So what to do if table has only one record ??? ho to write a simple while for "one table row" in this case ? Because i'm receving the same error :( – Simone Campagna Aug 23 '19 at 15:57
  • Why do you need a while loop for single record @SimoneCampagna? – hjpotter92 Aug 29 '19 at 04:27
  • Hi hjpotter92, thanks for answer. Simply i read aware that the method explained above doesn't work for table that has only one record. But maybe i'm wrong. I fix my problem removing a previous "fetch" operation on query results that "invalidate" later "fetch" operations on same query. – Simone Campagna Aug 29 '19 at 17:51