简体   繁体   中英

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.

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.

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());

Why no one say about "text text $array[key] text" syntax?

SELECT * 
FROM  Clients 
WHERE Username = '$new_username' 
AND   Username != '$_SESSION[Username]'

When you embed arrays in to strings, you have to seperate them by concatenating them or using curly braces.

$string = "text text {$array['key']} text";

or

$string = "text text " . $array['key'] . " text";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM