This question already has an answer here:
How can I prevent SQL injection in PHP?
You should use PDO Prepare
From the link:
Calling PDO::prepare() and PDOStatement::execute() for statements that will be issued multiple times with different parameter values optimizes the performance of your application by allowing the driver to negotiate client and/or server side caching of the query plan and meta information, and helps to prevent SQL injection attacks by eliminating the need to manually quote the parameters.
Here is an excerpt from the PHP website:
<?php $conn = new PDO('sqlite:/home/lynn/music.sql3'); /* Simple string */ $string = 'Nice'; print "Unquoted string: $string\n"; print "Quoted string: " . $conn->quote($string) . "\n"; ?>
The above code will output:
Unquoted string: Nice Quoted string: 'Nice'
Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.