简体   繁体   English

PHP PDO:从查询中获取第一列

[英]PHP PDO: gets first column from query

I have a pretty stupid question, but I can't get it to work immediately. 我有一个非常愚蠢的问题,但无法立即解决。
How do I load only one field of the result array of a query into a session (array) using a single PDO statement? 如何使用单个PDO语句将查询结果数组的一个字段仅加载到会话(数组)中?
I commented the missing code below: 我评论了以下缺少的代码:

public function getPermissions($user_role_id){
    if(!isset($user_role_id) || empty($user_role_id)){ 
        $_SESSION['user']['user_permissions'] = '';
    }else{
        $db = Database::get_database();
        $query = "
            SELECT 
                rp.role_id, rp.permission_id 
            FROM 
                role_permission_tbl rp 
            WHERE
                rp.role_id = :role_id"; 

            $query_params = array( 
                ':role_id' => $user_role_id
            );

            try 
            {
                $stmt = $db->prepare($query); 
                $result = $stmt->execute($query_params); 
            } 
            catch(PDOException $ex) 
            { 
                 die("Failed to run query: " . $ex->getMessage());
            }

            $row = $stmt->fetchAll();
            if($row){
                //I only want to retrieve the field "permission_id" 
                $_SESSION['user']['user_permissions'] = $row;
            }else{
                $_SESSION['user']['user_permissions'] = '';
            }
        }
}

Thanks 谢谢

After seeing your later comments, it looks as though you're wanting to save all permission data in a session variable so that you can look it up by permission ID: 在看到以后的注释之后,您似乎想将所有权限数据保存在一个会话变量中,以便可以通过权限ID进行查找:

$rows = $stmt->fetchAll();
foreach($rows as $row){
    //Add to session, keyed by permission ID.
    $_SESSION['user']['user_permissions'][$row['permission_id']] = $row;
}

//Then, if you want to see if said permission ID #21 exists:
if(isset($_SESSION['user']['user_permissions'][21])){
    echo 'This user has permissions with ID 21!';
    $permissionDetails = $_SESSION['user']['user_permissions'][21];
    var_dump($permissionDetails);
}

Can you try $row = $stmt-> fetch(); 你可以尝试$row = $stmt-> fetch(); instead of $row = $stmt->fetchAll(); 而不是$row = $stmt->fetchAll(); if it is fetch only one record from table, 如果仅从表中获取一条记录,

 $row["permission_id"];

Like any other "get it to work immediately" this question has contradicting conditions. 就像其他任何“立即启动它”一样,这个问题也存在矛盾的条件。
Like any other PHP code, it is ten times long than needed. 像其他任何PHP代码一样,它的长度是所需长度的十倍。
Like many other SO questions, it can be solved by quick manual lookup. 像许多其他SO问题一样,可以通过快速手动查找来解决。

In case you need your permissions in array 如果您需要在数组中的权限

public function getPermissions($user_role_id){
    $sql = "SELECT permission_id FROM role_permission_tbl WHERE role_id = ?"; 
    $stm = Database::get_database()->prepare($sql);
    return $stm->execute(array($user_role_id))->fetchAll(PDO::FETCH_COLUMN);
}

note that assigning variables inside functions is a very bad practice. 请注意,在函数内部分配变量是非常糟糕的做法。 So, better call it this way 所以,最好这样称呼它

$_SESSION['user']['user_permissions'] = $user->getPermissions($user_role_id);
  • isset() is useless in conjunction with empty() as latter covers the former. isset()与empty()结合使用是无用的,因为后者涵盖了前者。
  • both isset() and empty() are useless for the function variable too, as it is always set by design isset()和empty()对函数变量也都没有用,因为它总是由设计设置的
  • a verification for this particular input variable can be done, but for the sanely designed application it would be unnecessary. 可以对此特定输入变量进行验证,但对于合理设计的应用程序则没有必要。
  • setting a variable you are going to test with in_array() to an empty string will produce an error. 将要使用in_array()测试的变量设置为空字符串将产生错误。
  • there is no use for the alias with single table. 单表别名没有用。
  • PDO methods can be called dramatically shorter way, there is no use for stretching one simple query call to a whole screen of code. 可以将PDO方法称为更短的方法,没有必要将一个简单的查询调用扩展到整个代码屏幕。
  • echoing a system error message to a site user is an awful practice. 向站点用户回显系统错误消息是一种糟糕的做法。
  • the very manual page for the fetchAll() contains an exact example for this very question of getting single column out of the query result. 关于fetchAll()的非常手册的页面包含一个确切的示例,说明了如何从查询结果中获取单列。
  • there is no use for testing returned value explicitly, as it already contains either result or empty value (and luckily, fetchAll() will return even empty value of desired type). 显式测试返回的值是没有用的,因为它已经包含了结果或空值(幸运的是,fetchAll()会返回所需类型的空值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM