9

I would like to know how to escape strings in pdo . I have been escaping the springs like in the code bellow but now with pdo I do not know how to do it

$username=(isset($_POST['username']))? trim($_POST['username']): '';
$previlage =(isset($_GET['previlage']));
$query ="SELECT * FROM site_user 
WHERE username = '".mysql_real_escape_string($_SESSION['username'])."' AND  previlage ='Admin'";
$security = mysql_query($query)or die (mysql_error($con));
$count = mysql_num_rows($security);
Humphrey
  • 2,659
  • 3
  • 28
  • 38
  • Why are you using `mysql_real_escape_string` for session values? – Mr. Alien Feb 26 '13 at 14:35
  • Do not use depricated mysql_* functions. use PDO/MySQLi instead. – Boynux Feb 26 '13 at 14:37
  • 2
    @Mr.Alien — Presumably because the session contains text and not pre-escaped fragments of SQL. You should always escape text before inserting it into a data format or a string that will be evaluated as code. – Quentin Feb 26 '13 at 14:38
  • 3
    @Boynux — The question is asking *how* to do that! – Quentin Feb 26 '13 at 14:38
  • @Quentin I guess he must be using a regex to remove non username characters like `$#@%^!` etc, and am sure he fetches the data from the database and assigning it to username session – Mr. Alien Feb 26 '13 at 14:39
  • @Boynux am not using it iam asking a question on PDO this means I shifted to pdo – Humphrey Feb 26 '13 at 14:51

2 Answers2

23

Well, you can use PDO::quote, but, as said in its own docpage...

If you are using this function to build SQL statements, you are strongly recommended to use PDO::prepare() to prepare SQL statements with bound parameters instead of using PDO::quote() to interpolate user input into an SQL statement.

In your case it can look like this:

$query = "SELECT * 
            FROM site_user 
           WHERE username = :username AND previlage = 'Admin'";
$sth   = $dbh->prepare($query);
$sth->execute(array(':username' => $_SESSION['username']) );
raina77ow
  • 103,633
  • 15
  • 192
  • 229
3

mysql_* function will not work in PDO. WHY? Because PDO doesnt use mysql to connect to a databases, as far as input sanitization, PDO uses prepared statements you can find a good tutorial for that here: pdo

Nick
  • 171
  • 10