PDO Prepared Statement Execution - How to get only associative keys?

删除回忆录丶 提交于 2019-12-25 17:09:06

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/17262314/pdo-prepared-statement-execution-how-to-get-only-associative-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!