How do I escape a string in a query? I received the following error using my module:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 
You have an error in your SQL syntax; check the manual that corresponds 
to your MySQL server version for the right syntax to use near '%m-%d') = 
DATE_FORMAT(NOW(), '%Y-%m-%d') AND is_logout = 0' at line 1: SELECT id FROM 
ap_visits WHERE`current_ip` = '192.168.1.1' AND `url` = 
'http://www.mysite.com/php/4220/how-build-shopping-cart-w-checkout-php.html'' 
AND DATE_FORMAT(date_start, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d') AND 
is_logout = 0; Array ( ) in test_module_check() 
(line 164 of /var/www/clients/client1/web2/web/sites/all/modules/test_module/test_module.module).


The error here is in the value of url column. It has an apostrophe at the end. So my question is on how can I escape this value so the apostrophe will not be an issue?

I am using db_query. This is my code:

$sql = "SELECT id FROM ap_visits WHERE`current_ip` = '$current_ip' AND `url` = '$url' AND DATE_FORMAT(date_start, '%Y-%m-%d') = DATE_FORMAT(NOW(), '%Y-%m-%d')  AND is_logout = 0";

$result = db_query($sql);
You should do 

$sql = "SELECT id FROM {ap_visits}  WHERE current_ip = ':current_ip' AND url = ':url' AND DATE_FORMAT(date_start, '%%Y-%%m-%%d') = DATE_FORMAT(NOW(), '%%Y-%%m-%%d')  AND is_logout = 0";

$result = db_query($sql, array(':current_ip'=&gt;$current_ip, ':url'=&gt;$url));