Query with sprintf & mysql_real_escape_string

Discussion in 'PHP' started by junandya, Jan 24, 2008.

  1. #1
    Hi,

    i have a query without sprintf & mysql_real_escape_string like this:
    $query_src = "SELECT * FROM ability WHERE software LIKE '$theWord,%' OR software LIKE '%,$theWord,%' OR software LIKE '%,$theWord'";
    
    $result_query = mysql_query($query_src,$connection) or die (mysql_error());
    PHP:
    but i want to use this query with mysql_real_escape_string, could someone here convert the query script as i wish please.

    my problem is i dont understand how to use %s in sprintf here in my query case. i have read http://id.php.net/sprintf and http://id.php.net/mysql_real_escape_string, but still have problem with it.

    Thank you B4
     
    junandya, Jan 24, 2008 IP
  2. kreoton

    kreoton Peon

    Messages:
    229
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #2
    I dont think that you need this. just use % in your query once like this:

    $theWord = mysql_real_escape_string($_POST['q']); //but i prefere addslashes...
    
    $query_src = "SELECT * FROM ability WHERE software LIKE '%$theWord%'";
    
    /*
    if search query is 'apple' this query would match:
    	- APPLE
    	- Apple
    	- Apples
    	- apple
    	and so on...
    */
    PHP:
     
    kreoton, Jan 25, 2008 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #3
    mysql_real_escape_string() is safer than addslashes(), in terms of SQL injection.
     
    nico_swd, Jan 25, 2008 IP
  4. junandya

    junandya Member

    Messages:
    79
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #4
    Why the query should be like that is because the content of table 'ability' is like this:

    ID -- SOFTWARE
    1 -- 1,2,4,6,10,13
    2 -- 3,7,9,1314
    3 -- 3,4,5,6,13,15
    4 -- 1,10,15
    5 -- 13,14,15

    for example, if i want to get data where software is = 13.

    Is it OK if i dont use sprintf as the query that you give?
     
    junandya, Jan 25, 2008 IP
  5. kreoton

    kreoton Peon

    Messages:
    229
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #5
    if you use my query where softeare = 13 you get 1,2,3 and 5th rows.
     
    kreoton, Jan 25, 2008 IP
  6. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #6
    Yes it is.
    Using sprintf with LIKE queries can actually get confusing at times because in order to use % with sprintf you need to double them up to escape them.

    $a = mysql_real_escape_string($a);
    $b = mysql_real_escape_string($b);
    $sql = 'SELECT * FROM TABLE
    		WHERE a LIKE \'%s,%%\'
    			OR b LIKE \'%%%s,%%\'';
    $query = sprintf($sql, $a, $b);
    PHP:
     
    joebert, Jan 25, 2008 IP