Matt
Matt

Reputation: 1103

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.

Upvotes: 6

Views: 41095

Answers (4)

Salman Arshad
Salman Arshad

Reputation: 272416

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

Upvotes: 8

Crusader
Crusader

Reputation: 1200

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

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

Upvotes: 1

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17772

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";

Upvotes: 0

Michiel Pater
Michiel Pater

Reputation: 23053

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.

Upvotes: 12

Related Questions