Reputation: 1129
When I use prepared statements do I have to use functions like mysqli_real_escape_string
or are the executed automatically?
For example should I just use this
$stmt = $mysqli->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam('sd', $name, $value);
or do I have to use something like this
$stmt = $mysqli->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam('sd', mysqli_real_escape_string($name), mysqli_real_escape_string($value));
Which functions are recommended to avoid sql injections?
Upvotes: 0
Views: 91
Reputation: 93636
No, you do not need to escape your parameters. In fact, escaping variables that you then pass in to a parametrized query is an error and will give you incorrect results.
Upvotes: 3
Reputation: 3251
Prepared statements automatically scrub what you're inserting. When you do the following:
$stmt = $mysqli->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
That bindParam function is doing all the necessary cleaning for you and then inserting that value into the query string.
Fun fact, prepared statements are a hack built on top of a hack in their fundamental idea :)
Upvotes: 1
Reputation:
When using parameterized queries, the escaping is done by the API. your first method is correct.
If you are doing raw text queries, then you should escape your parameter values.
Upvotes: 2