I have done my research and have decided to use prepared statements in my queries, all I ask if there is anything I should know, good or bad about switching to normal mysqli
Most people do confuse prepared statements with placeholders.
It's general idea of using placeholders is really great, while prepared statements is just a subset of placeholders with limited functionality.
Placeholders are great because:
As for the performance issues everyone is talking about, most of time prepared statements are slower than regular query. However the difference going to be unnoticeable in both cases.
Escaping bad characters is still needed, but the library does it automatically for all parameters you bind. It's just slightly more convenient, and prevents the programmer from forgetting to sanitize a value.
However, note that this automatism is limited to parameters!
The following query is safe, because bind_param()
takes care of escaping:
$code = $_GET["code"];
$name= $_GET["name"];
$percentage= $_GET["percentage"];
$stmt = $mysqli->prepare("INSERT INTO items VALUES (?, ?, ?)");
$stmt->bind_param('iss', code, $name, $percentage);
$stmt->execute();
the following query is unsafe, because anything you put directly into the query will not be escaped automatically:
$tablename = $_GET["prefix"]."_items";
$code = $_GET["code"];
$name= $_GET["name"];
$percentage= $_GET["percentage"];
---- UNSAFE! ----
$stmt = $mysqli->prepare("INSERT INTO `$tablename` VALUES (?, ?, ?)");
$stmt->bind_param('iss', $code, $name, $percentage);
$stmt->execute();
that said, one shouldn't be using dynamic table names like shown in this example anyway. But the point stands: Be careful, even with parametrized queries!
The only downside I can think of is that you can't see the final query any more for debugging (because it gets assembled only on server side).
There are at least two advantages :
?
unnamed, or :name
named) the values you insert there are automatically quoted.