// the connection
$db = new PDO("mysql:host=localhost;dbname=db", 'root', 'secret');
// regular query, $st is a statement object returned containing results
$st = $db->query("SELECT * FROM table WHERE field = ".$dangerous);
// $st is now a prepared statement, values will be bound later
$st = $db->prepare("SELECT * FROM table WHERE field = ?");
// bind values and execute, no need to escape as the data is separated
Why create your own solution that may contain security holes when there is a built in function specifically for the purpose.
If you are using mysql_query or mysqli_query then you need to use mysql_real_escape_string or mysqli_real_escape_string respectively on each individual field before inserting them into the query so that their content will not get confused with the query itself. A better alternative is to use a prepare statement with either mysql/PDO or mysqli to keep the data completely separate from the query.