Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape strings in pdo? [duplicate]

Tags:

php

mysql

pdo

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);
like image 200
Humphrey Avatar asked Feb 26 '13 14:02

Humphrey


2 Answers

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']) );
like image 102
raina77ow Avatar answered Oct 10 '22 03:10

raina77ow


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

like image 20
Nick Avatar answered Oct 10 '22 04:10

Nick