PDO Prepared Statement Execution - How to get only

2019-09-19 09:52发布

This should be a simple thing to solve...

I have got these estatements when a user logs in:

    $query = $conn->prepare("SELECT * FROM admins WHERE username = :user AND password = :pass");    
    $query->bindValue(":user", $user);
    $query->bindValue(":pass", md5($pass));
    $query->execute();

Now if the user exists, I return the user information from the database, but if not, I return false instead...

    if($query->rowCount() > 0) {
        $admininfo = $query->fetchAll(PDO::FETCH_ASSOC);
    } else {
        return false;
    }

But when I var_dump the variable $admininfo I get an array with a number key before the actual array... like this:

array (size=1)
  0 => <---- I DONT KNOW WHERE THIS COME FROM. I USED PDO::FETCH_ASSOC
array (size=9)
  'id' => string '1' (length=1)
  'username' => string 'admin' (length=5)
  'password' => string '21232f297a57a5a743894a0e4a801fc3' (length=32)
  'permissionid' => string '1' (length=1)
  'name' => string 'Administrador' (length=13)
  'lastname' => string 'Softing' (length=7)
  'phonenumber' => null
  'cellphonenumber' => null
  'info' => null

I will put this information inside the SESSION array, so I want to access it by $_SESSION["admininfo"]["username"] or $_SESSION["admininfo"]["phonenumber"]

but I have to put something like this instead: $_SESSION["admininfo"][0]["phonenumber"].

How can I remove that 0 from the keys? Thank you!

2条回答
神经病院院长
2楼-- · 2019-09-19 10:37

You're using fetchAll. This will give you an array of DB rows -- of all the rows that were matched.

Use fetch in a while loop to go through individual rows one by one.

查看更多
Animai°情兽
3楼-- · 2019-09-19 10:39

According to the documentation for fetchAll, it will return an array of elements. This is because it is getting all of the rows in the table that match your criteria. In your case, you are only getting back one row, located at index 0. If you know you only want one result, use fetch instead of fetchAll. It will get rid of the 0.

查看更多
登录 后发表回答