Use prepared statements. They are designed for this purpose. Furthermore you should note that building SQL queries the way you are actually doing is vulnerable against SQL injections. Or in other words it this the best example for vulnerable code. What if a hacker posts SQL statements? Prepared statements will prevent from this as it separates query data from the query syntax.
In PHP you could use PDO
for prepared statemtens (among other extensions). Here comes a short example:
$pdo = new PDO('...');
$stmt = $pdo->prepare('SELECT FROM table WHERE id=:id AND title=:title ...');
$stmt->execute(array('id' => 1, 'title' => 'test'));
Update:
In comments you said that you'll have to use the mysql_* extension. If doing so you should know, that you'll have to escape every single value to prevent from SQL injections. Like this:
// first(!!!) connect to mysql. this is important because
// mysql_real_escape_string() will need information about
// the current connection's encoding to work properly
if(!mysql_connect(...) && mysql_select_db(...)) {
die('mysql connection error');
}
// escape values
$id = mysql_real_escape_string($_POST['id']);
$title = mysql_real_escape_string($_POST['title']);
...
// now you could just use double quotes `"` to insert vars into the query string:
mysql_query("SELECT * FROM `table` WHERE id = $id AND title = '$title'");
If you need this additional info:
Note: There is a syntax called curly syntax using {}
which can be used to access arrays in double quoted "
strings. I've not used it in the example, as it is not recommended to place post vars in a query without escaping them first. However here comes a syntax example:
$array = array('foo' => 'bar');
$string = "Hello {$array['foo']}";