2

Not new to PHP, but only a day old to PDO. Surely I am doing something wrong here.

 $query = $conn->prepare("SELECT * FROM admins WHERE username = :username AND password = :password"); $query->execute(array('username' => $username,'password' => sha1($password))); $result = $query->fetchAll(PDO::FETCH_ASSOC); if (count($result) > 0) { $_SESSION['user']['who'] = $result[0]['who']; $_SESSION['user']['email'] = $result[0]['email']; $_SESSION['user']['username'] = $result[0]['username']; echo REFRESH; } else { $message = "Invalid username / password."; } 

the only way I can declare those $_SESSIONS properly is if I use $result[0]['fieldName']; How can I just access it via $result['fieldName']; ?

2 Answers 2

9

fetchAll, as the documentation says, retrieves an array of all fetch data simultaneously. Since you are using FETCH_ASSOC, an array of associative arrays is fetched. If you know for certain that only one column is being returned or are only interested in the first column returned, just use fetch. Otherwise you have to iterate over the fetchAll results or do what you've done.

Sign up to request clarification or add additional context in comments.

2 Comments

Alright, so what would the proper test case be for it not returning anything if I use just fetch? First thought would be (!empty($result)) ? //log in : //invalid
fetch will return a falsy value if there are no rows. You could also check rowCount. Either if ($query->rowCount) or if (!$row = $result->fetch()) will do.
-1

use:

foreach( $result as $row ) { $_SESSION['user']['who'] = $row['who']; .... and so on } 

2 Comments

Seems silly to use foreach when it overwrites the same variable each time, and when you know there's only one element in the array to begin with.
True - go with @explosion pills approach.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.