728x90


I am trying to find the number of rows that match a specific pattern. In this example, all that START with "123":

This is working:

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '123%'");
$count = mysql_num_rows($query);

The problem is the LIKE will vary, so I'm trying to define it in the script, then execute the query, but this is NOT working:

$prefix = "123";
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix.'%'");
$count = mysql_num_rows($query);

How can I get this query to work properly in the second example?

EDIT: I've also tried it without the period (also not working):

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE $prefix'%'");
shareimprove this question
   
John, something that I have found helps me when using variables in strings, is to use the curly braces. $var1 = "foo"; $var2 = "{$var1} bar"; echo $bar2; Will output: foo bar and you don't have to worry about concatenation, etc etc. Doesn't work as you may think with single quotes for strings, however. – Blake Apr 13 '12 at 0:10 

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

shareimprove this answer
   
Fantastic. Thank you so much! – JROB Apr 12 '12 at 23:56
2 
There is a danger of injection if you are using any user-inputted data. There is zero danger for: $var = "rawr"; ... query("SELECT * FROM table WHERE col='{$var}'"; You are controlling your own data on-server. – Blake Apr 13 '12 at 0:06 
   
@Blake: Obviously, but I feel obliged to say it anyway. Code has a way of being adapted to contexts other than the one it was meant for. – Jon Apr 13 '12 at 0:14
   
@Jon, Surely. However, you have to specify that queries can be vulnerable to injections... with user-inputted data. There's a difference between saying "Look at that house" and "Look at that house on fire." :) – Blake Apr 13 '12 at 1:38
   
ertertg ertferf – user609306 Mar 8 '14 at 17:58 


'WEB' 카테고리의 다른 글

How to set clearfix and define  (0) 2018.01.24
[PHP] swtich  (0) 2018.01.23
explode  (0) 2018.01.22
[PHP] mysqli::num_rows  (0) 2018.01.14
[PHP] filter_var function vs number_format  (0) 2018.01.14

+ Recent posts