Ukjent
Ukjent

Reputation: 823

Php pdo statement vs MsSQL escaping?

Similar questions have probably been asked before, and sry for that. Need to be sure that i protect from SQL injections correct.

I have just converted my php sql statments to pdo statments. For the old sql queries I used to use mysql_real_escape_string, strip_tags(), and maybe htmlenteties()(not sure if id did html).

Is it necessery to use anything like this in the pdo statments. Have heard some places that this is not necessary in pdo. Whats true/false ?

And: I have always used to write the queries like the first example below:

SELECT `id` , `password` FROM  `users` WHERE `username` = '$username'
SELECT id, password FROM users WHERE username = '$username'

Is the example 1 more safer(from sql injections) than example 2 or is it just wasted time doing it ?

Upvotes: 1

Views: 333

Answers (2)

Palladium
Palladium

Reputation: 3763

They say you don't need to escape strings in PDO because they use prepared statements. If you're just using the PDO query() method like in mysql, that's no more secure than just using mysql. As for the examples you've given, they're both equally unsafe; they're both equally vulnerable to injection (and they're very vulnerable to injection). On a tangential point, the mysqli extension has one advantage over PDO in the sense that you cannot carry out multiple SQL statements over one mysqli_query(). This offers some (not full) protection against some (again, not all) injection attempts, especially the ones to make new superusers and the like.

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838116

If you are using PDO you should be using prepared statements with parameters. There are some examples in the documentation.

/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();

If you use this approach then there is no need for escaping strings.

Upvotes: 4

Related Questions