Try to use PHP's PDO for database access if you can. There are two important reasons for this:
- You can use PDO's prepare function to compile your query. This is efficient if you need to issue the same query with different input (as is often the case). So, compile once and execute multiple times.
- Compiling the query with prepare has other nice effects. Once the query is compiled, the database engine knows the exact syntactic structure of the query, and does not allow any input that changes this syntactic structure. This is good because in SQL injection, the injected input changes the syntax of the query.
Warning: This doesn't prevent all kinds of SQL injection, but it prevents the most common kind.
References:
- Are PDO prepared statements sufficient to prevent SQL injection?
- http://php.net/manual/en/pdo.prepare.php