This is a design question, I've been thinking about this for a while.
I would like to separate the SQL queries inside independent files or memory locations (for faster access).
The queries will be stored like this:
SELECT .... WHERE col = ?
When the query is needed, it is fetched from it's location.
A (less maintainable) example alternative would be:
$sql = "select ..... where col=". prevent_injection($val) ." and ....";
Benefits:
Disadvantages:
Any feedback on this approach?
You should have a look at the MVC (Model View Controller) architectural pattern. It will allow you to achieve your goal: Separation of data, logic and presentation.
In MVC, your models will handle all SQL related logic, so that the other two layers will never have to deal with queries.
Have a look at PHP Frameworks which implement the MVC pattern, they will greatly simplify applying this pattern to your project. My personal favourite is Laravel 4, but there are lots of others, such as FuelPHP, CodeIgniter, CakePHP et al.
Most of these frameworks also have caching mechanisms as a bonus and they are able to utilize other means of speeding up your web application: Redis and Memcache, for example.
Usually I use two ways for preventing SQL injection.
ORMs like propel, it handle all the SQL injection issue in itself. You don't need to care the details. And several MVC frameworks are using ORMs.
The PHP Data Objects (aka: PDO) extension. You could write your code like below. it also handle all the SQL injection issue in itself
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)"); $stmt->bindParam(':name', $name); $stmt->bindParam(':value', $value); $stmt->execute();
According to benefits you want, I suggest you can use PDO for clear SQL and keep it light-weight.