0

At login, I do session_start() and then set the following session variables:

$_SESSION['id'] = $row['id'];
$_SESSION['role'] = $row['role'];
$_SESSION['customer_id'] = $row['customer_id'];

Later, in another php I check the value of these $_SESSION variables to determine which SELECT statement will be used to access the database as follows:

$sess_cid = $_SESSION['customer_id'];

if ($_SESSION['role'] = 1) {
    $sql = 'SELECT  * FROM  my_table';

} elseif ($_SESSION['role'] = 2) {
    $sql = 'SELECT  * FROM  my_table WHERE  id = "$sess_cid"';

} else {
    echo "not authorized to access app";
}

Am I not formatting the if() properly? Everything should be set to INT value in the database.

Bricked
  • 115
  • 1
  • 11

1 Answers1

1

Try this:

$sess_cid = $_SESSION['customer_id'];

if ($_SESSION['role'] == 1) {
    $sql = 'SELECT  * FROM  my_table';

} else if ($_SESSION['role'] == 2) {
    $sql = 'SELECT  * FROM  my_table WHERE  id = "$sess_cid"';

} else {
    echo "not authorized to access app";
}

You have to compare the session value using "==" operator.

I would even suggest you to use Switch statements over multiple if else.

$sess_cid = $_SESSION['customer_id'];

switch($_SESSION['role']) {
   case 1:
    $sql = 'SELECT  * FROM  my_table';
    // do whatever you want to do here..
    break;

   case 2:
    $sql = 'SELECT  * FROM  my_table WHERE  id = "$sess_cid"';
    // do whatever you want to do here..
    break;

   default:
    echo "not authorized to access app";
    break;
}
Satish Saini
  • 2,880
  • 3
  • 24
  • 38
  • Sani - thank you. I wondered about the == but I saw many examples of = online. So simple. Thank you – Bricked Apr 13 '17 at 15:16
  • @Bricked Great! Would you mind choosing it the right answer? ;) – Satish Saini Apr 13 '17 at 15:17
  • now the only minor thing is my SELECT is not pulling any records. I have records with id = 8, and $sess_cid = 8, but they are not pulling. I wonder if I need to convert $sess_cid to intval? – Bricked Apr 13 '17 at 15:27
  • Try this "SELECT * FROM my_table WHERE id = $sess_cid" This will take the input parameter as it is. If that doesn't work then post the code that you are using to retrieve the results after your query. – Satish Saini Apr 13 '17 at 15:30
  • if ($_SESSION['role'] == 1) { $sql = 'SELECT * FROM my_table'; } elseif ($_SESSION['role'] == 2) { $sql = 'SELECT * FROM my_table WHERE id = "$cust_id"'; } else { echo "not authorized to access app"; } foreach ($pdo->query($sql) as $row) { ... – Bricked Apr 13 '17 at 15:55
  • Try to write the query in double quotes and remove the quotes around your variable $cust_id. Write it like this "SELECT * FROM my_table WHERE id = $cust_id" – Satish Saini Apr 13 '17 at 15:58