-2

I hope someone can help me on this? Here's my select statement based on a session variable.

$users = 'SELECT * FROM wbcusers WHERE username = "'.$_SESSION['user'].'" ';

I want to be able to SELECT IF the session variable 'user' exists... IF NOT, I do not want to select anything and cancel the database query so I don't see a 'Notice: Undefined index: error' notice?

Any help on how this is done would be very much appreciated.

Thank you. Steve

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141

2 Answers2

1

Set your users array to an empty array initially, then fill it with data if and only if the session variable you need is set.

$users = [];

if (isset($_SESSION['user'])) {
  $sql = "SELECT * FROM wbcusers WHERE username = ?";
  $stmt = $pdo->prepare($sql);
  $stmt->execute([$_SESSION['user']]);
  $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

P.S.: Please use query parameters like above, instead of ugly string concat nonsense. It's way easier to write the code, and you don't have to worry about SQL injection vulnerabilities.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
-2
if (isset($_SESSION['user'])) {
    $users = 'SELECT * FROM wbcusers WHERE username = "'.$_SESSION['user'].'" ';
    ....
}
else
{
   //something else
}
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72