robert_gsfame Posted April 15, 2010 Share Posted April 15, 2010 How to create a query using LIKE clause assume mysql_query(sprintf("SELECT * FROM table WHERE name LIKE '% %'", mysql_real_escape_string($username) Where should i put '%s' thx Quote Link to comment Share on other sites More sharing options...
andrewgauger Posted April 15, 2010 Share Posted April 15, 2010 How are you trying to use LIKE? Do you have "apple" and you want to match "apple" | "apples"? When you put LIKE '% %" you are going to match anything with a space in it. When you match LIKE '%s' you will match anything ending in s. What is it you want to match? Quote Link to comment Share on other sites More sharing options...
robert_gsfame Posted April 15, 2010 Author Share Posted April 15, 2010 cause i have "apple,orange,grapes" and i want to match whether i have apple or not in that record therefore i use LIKE % % but i am confused when combining it with mysql_real_escape_string() Quote Link to comment Share on other sites More sharing options...
andrewgauger Posted April 15, 2010 Share Posted April 15, 2010 lol, I was reading it as 2 lines, I know what you are talking about. mysql_query(sprintf("SELECT * FROM table WHERE name LIKE '%%%s%%'", mysql_real_escape_string($username); 2 % for every literal "%" in sprintf and one for the %s. Quote Link to comment Share on other sites More sharing options...
robert_gsfame Posted April 15, 2010 Author Share Posted April 15, 2010 okay...this problem solve but what if i create a dynamic query for example $a=$_GET['a']; if(!empty($a)){ $a="AND name LIKE'%".$a."%'";} and i wish this query to be execute using mysql_real_escape_string() SELECT * FROM table1 WHERE column1='record1' $a so that when $a not empty i will have this query SELECT * FROM table1 WHERE column1='record1' AND name LIKE '%a%' else SELECT * FROM table1 WHERE column1='record1' Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted April 15, 2010 Share Posted April 15, 2010 And the issue is? Please ask questions if you want answers. Quote Link to comment Share on other sites More sharing options...
andrewgauger Posted April 15, 2010 Share Posted April 15, 2010 $a=stripslashes(mysql_real_escape_string($_GET['a'])); //original example says a="apples" $sqlLike=is_Null($a) ? " AND name LIKE '%$a%' : ""; $sql="SELECT * FROM table1 WHERE column1 = 'record1'".$sqlLike; should set sql= SELECT * FROM table1 WHERE column1 = 'record1' AND name LIKE '%apples%' I believe if you mysql_real_escape it surrounds the value with ' and you need to stripslashes on it to get rid of them. Depends on your installation though, safer to use it in this example. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.