tags:

views:

36

answers:

1

I have a pdo function that fetches usernames and user ids from the database. When I run the function i get different results.

print_r gives

Array ( [ID] => 58 [username] => abdullatif )

and foreach gives me

5-5a-a

There is one row that matches the pdo query in the database.

public function getUserCredentials($userName, $password){
$this->db   = new Dbpdo_Database(); 
$this->db->connect();
try{  
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $dbh->prepare("SELECT 
            ID 
          FROM 
            administrators 
          WHERE 
            username = :username 
          AND 
            user_password = :password
          LIMIT 1");  


    $stmt->bindParam(':username', $userName, PDO::PARAM_STR);
    $stmt->bindParam(':password', $password, PDO::PARAM_STR);
    }

    $stmt->execute();

    /*** fetch the results ***/
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    return $results;

    /*** close the database connection ***/
    //$dbh = null;
}
catch(PDOException $e){
    echo $e->getMessage();
  } 
}

$results = $mydb->getUserCredentials($userName, $password);

foreach ($results as $row){
echo $row['ID'].'-'.$row['username'];
}

print_r($results);

Any hints as to whats wrong would be much appreciated. Thanks in advance.

+1  A: 

Your $results array is one-dimensional - it has an ID and a username. Your foreach is looking for a two-dimensional array, with each row containing an ID and a username. Change it to:

foreach($results as $key => $value) {
    echo $key . '-' . $value;
}

and you should get:

ID-58
username-abdullatif
adam
if i wanted just the result of the id how would i do that?
CoderX
`$results['ID']` (this may change if more than one matching row is returned, depending on your script)
adam