Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding session variable into MYSQL query using PHP

Im trying to pass two variables into a mysql query, and its getting stuck when passing the session variable in below:

$check = mysql_query("SELECT * 
                      FROM Clients 
                      WHERE Username = '$new_username' 
                      AND Username != '$_SESSION['Username']'") or die(mysql_error()); 

Any tips? Thanks in advance.

like image 490
Matt Avatar asked Feb 11 '11 12:02

Matt


2 Answers

It is because your single quotes '$_SESSION['Username']' have been ended by the value in the session. Changing this to '" . $_SESSION['Username'] . "' will solve the problem.

like image 152
Michiel Pater Avatar answered Sep 20 '22 23:09

Michiel Pater


This will work but this is VERY, VERY BAD:

$check = mysql_query("
    SELECT * 
    FROM  Clients 
    WHERE Username = '$new_username' 
    AND   Username != '{$_SESSION['Username']}'
") or die(mysql_error());

This too shall work and recommended way of doing it:

$check = mysql_query("
    SELECT * 
    FROM  Clients 
    WHERE Username  = '" . mysql_real_escape_string($new_username) . "' 
    AND   Username <> '" . mysql_real_escape_string($_SESSION['Username']) . "'
") or die(mysql_error());
like image 40
Salman A Avatar answered Sep 18 '22 23:09

Salman A