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