Is this the best way to do it?
Should I do this to every value in every query? GET and POST?
Is addslashes(mysql_real_escape_string())
overkill?
Is this the best way to do it?
Should I do this to every value in every query? GET and POST?
Is addslashes(mysql_real_escape_string())
overkill?
If you're using mysql_query() then yes, mysql_real_escape_string() is the best way. And yes, you have to apply it to every parameter you mix into your sql statement. E.g.
$query = "
SELECT
x,y,z
FROM
foo
WHERE
a = '". mysql_real_escape_string($_POST['a'], $mysql) . "'
AND b = '". mysql_real_escape_string($_POST['b'], $mysql) . "'
";
But you can also use prepared statements, e.g. with the pdo module. The parameters are transferred apart from the sql statement and therefore do not require escaping. It's more secure (since you can't forget the escaping or doing it wrong/for the wrong charset), often faster and very often even simpler than mixing the parameters into the statement. e.g.
$pdo = new PDO('mysql:host=localhost;dbname=test', '..', '..');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("
INSERT INTO
foo (x,y,z)
VALUES
(:x,:y,:z)
");
$stmt->bindParam(':x', $x);
$stmt->bindParam(':y', $y);
$stmt->bindParam(':z', $z);
// insert all records (0,0,0) ... (0,1,0) ... (9,9,9)
for($x=0; $x<10; $x++) {
for($y=0; $y<10; $y++) {
for($z=0; $z<10; $z++) {
$stmt->execute();
}
}
}
edit: and addslashes(mysql_real_escape_string()) is not only overkill but also wrong.
You need to have a mysql connection already established in your script to use mysql_real_escape_string().
Have you tried PDO?
It prevents mysql injection attacks automatically.
$db = new PDO("mysql:host=$dbhost;dbname=$default_dbname", $dbusername, $dbuserpassword);
$st = $db->prepare ('SELECT * from my_table WHERE owner= ? and dog = ?');
$st->execute (array('Bob', 'Rex'));
$data = $st->fetchAll();
Might want to use htmlentities() on output though.