TheFoss
TheFoss

Reputation: 65

What is the difference in how you would have to access these two PHP arrays?

I have two PHP arrays in a section of a website I'm building for a class. One contains data that I created with a simple foobar array bit, and the other is created from a fetchAll() PDO call. I can't access the PDO array's element for some reason, so I created a sample array and called var_export() on both arrays to see if there were any differences. Here is the code:

if ($dao->userExistsLogin($_POST["email"], $_POST["password"]))
{
    $useremail = $_POST["email"];
    $_SESSION["authenticated"] = "true";
    $logger->LogDebug("email from post array in login handler: " . $_POST["email"]);
    $user_results = $dao->getIDFromEmail($useremail);
    $logger->LogDebug(print_r($user_results, true));
    $array = [
        "foo" => "bar",
        "bar" => "foo",
    ];
    $logger->LogDebug(var_export($array, true));
    $logger->LogDebug(var_export($user_results, true));
    $logger->LogDebug(gettype($user_results));
    $_SESSION['user_id'] = $user_results['id'];
    header("Location: http://localhost/WIWO/user_account.php");
} 

The GetIDFromEmail function is here:

    public function getIDFromEmail($email)
    {
        $conn = $this->getConnection();
        $getIDFromEmailQuery = "SELECT * FROM user WHERE email=:email";
        $query = $conn->prepare($getIDFromEmailQuery);
        $query->bindParam(":email", $email);
        $query->execute();
        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        $this->logger->LogDebug(print_r($result, true));
        return $result;
    }

And here's what's in my logger from the var_export() commands:

2020-10-31 17:57:10 - DEBUG --> array (
  'foo' => 'bar',
  'bar' => 'foo',
) 
2020-10-31 17:57:10 - DEBUG --> array (
  0 => 
  array (
    'id' => '251',
    'email' => 'heck',
    'institution' => 'heck',
    'access' => '1',
  ),
) 

Why can I not access the second array at $_SESSION['user_id'] = $user_results['id'];? For some reason that line totally fails to do anything. I know the session is started and correct because other variables stored in the SESSION superglobal are showing up correctly, but the user_id never gets set. Does it have something to do with "0 =>" showing up in the var_export() of the second array? I notice that doesn't show up in the first array - is the second array malformed or something?

Upvotes: 0

Views: 31

Answers (1)

Ro Achterberg
Ro Achterberg

Reputation: 2694

You're using PDOStatement::fetchAll(), which will always return an array of rows. Instead you might want to use PDOStatement::fetch() which will return precisely one row.

I haven't seen the userExistsLogin() method, but you could probably simplify your code if you have that method return the user id on success, and something falsey (e.g. 0, FALSE or NULL) on error. This will not only reduce code complexity, but it will reduce database load as well.

Upvotes: 2

Related Questions