user2345507
user2345507

Reputation: 17

What is the proper way to escape a $_SESSION username for use in a mysql query?

I am using the stored $_SESSION username:

$usernameunesc = htmlentities($_SESSION['username'], ENT_QUOTES, 'UTF-8');

and escaping the variable as follows:

$username = mysqli_real_escape_string($link, $usernameunesc);

and then using it to perform the following query:

$query = mysqli_query($link, "SELECT id FROM users WHERE username = '".$username."'");

The last query returns an output of

1111

If I remove $username from the query and change it to 'demo' (which is what the username actually is) the query returns an id of 12 successfully, but using the $username variable does not work. Am I not properly escaping the string? Is there a better way to do this? By the way, I can also perform the query in the SQL command line and it works fine, so I know the query isn't the problem.

Upvotes: 0

Views: 117

Answers (1)

Youn Elan
Youn Elan

Reputation: 2452

As you are using mysqli, I suggest you use a prepared statement - it will automatically escape the variable.

if ($stmt = $mysqli->prepare("SELECT id FROM users WHERE username =?")) {

    /* bind parameters for markers */
    $stmt->bind_param("s", $usernameunesc);

    /* execute query */
    $stmt->execute();
}

Full example right here http://php.net/manual/en/mysqli.prepare.php

Upvotes: 1

Related Questions