MGM
MGM

Reputation: 223

How to get particular column name and assigned an array using PHP?

I have the following columns in users table

id username  rights_reports  rights_notify  rights_users  rights_supporting  lang  deleted

1   admin     1                 1               1           1                 en    0
2   subadmin  1                 0               0           1                 en    0   

I want to check the access permission for users.

<?php

$sql = "SELECT * FROM `users` WHERE `id`='1'";
$resul = tdbQuery($sql);
$data = $result->fetch_assoc();
$permission = array('rights_reports'=>$data['rights_reports'],'rights_notify'=>$data['rights_notify'],'rights_users'=>$data['rights_users'],'rights_supporting'=>$data['rights_supporting']);
$_SESSION['access']=$permission;
?>

Here, can I get the particular column from the table like, COLUMN NAME LIKE rights_ and this value automatically assigned array?

Thanks

Upvotes: 2

Views: 59

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157870

$sql = "SELECT rights_reports,rights_notify,rights_users,rights_supporting 
        FROM `users` WHERE `id`='1'";
$_SESSION['access'] = tdbQuery($sql)->fetch_assoc();

better yet, you have to store rights in the rows, not columns. And use PDO instead of mysqli. So, the proper code would be

$sql = "SELECT r.name, ur.value FROM user_rights ur, rights r 
        WHERE user_id=? AND r.id = ur.rights_id";
$stmt = $pdo->prepare($sql);
$stmt->execute([1]);
$_SESSION['access'] = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

tables are: rights

id | name
1  | reports
2  | notify
3  | users
4  | supporting

and user_rights

user_id | rights_id
      1 |         1
      1 |         4

This is how databases intended to work

Upvotes: 2

Related Questions