Reputation: 6057
Here's how I currently do it:
$db->query(sprintf('INSERT INTO pages (title, content) VALUES ("%s", "%s")', $db->esc($title), $db->esc($content)));
As you can see I'm manually escaping each string in the above query by passing each string to my $db->esc() method.
First let me indicate that I don't want to use prepared statements.
The best idea I can come up with is to have my $db->query() method wrap sprintf() and automatically call $db->esc() on each string conversion specification - like this:
$db->query('INSERT INTO pages (title, content) VALUES ("%s", "%s")', $title, $content);
That looks great to me, but now my question becomes how do I correctly parse out all the string conversion specifications from the format string and call $db->esc() on each respective argument(before passing that all to sprintf())?
Would you do it a different way?
Upvotes: 0
Views: 995
Reputation: 157887
First let me indicate that you want to use prepared statements.
The very automatic "escaping" (although it have to be called formatting) you are talking of, is what exactly prepared statements are for.
Prepared statement is not necessarily have to be based on a database-supported native prepared statement. The general idea of prepared statement is to represent some query part with placeholder and to apply some formatting when replacing a placeholder with actial data. So - your approach is already using placeholders AKA prepared statements.
But there are some important things you missed
esc()
functionSo, here you go - the code for such a wrapper you're asking for , which does correct formatting, and thus you will have your queries no less secure than with PDO. Although with all the limitations which PDO has.
So, if you want to properly format everything, that may may be added to the query, you will need another wrapper, a more complex one: safeMysql
Upvotes: 1
Reputation: 15464
You should read about prepared statement.
Prepare: The statement template is created by the application and sent to the database management system (DBMS). Certain values are left unspecified, called parameters, placeholders or bind variables (labelled "?" below):
`INSERT INTO PRODUCT (name, price) VALUES (?, ?)`
The DBMS parses, compiles, and performs query optimization on the statement template, and stores the result without executing it. Execute: At a later time, the application supplies (or binds) values for the parameters, and the DBMS executes the statement (possibly returning a result).
And it's implimentation in PHP: PDO, MySQLi, PostgreSQL and other. So, there is no reason to implement it by yourself. Just use it.
Upvotes: 2