What's wrong with my use of the LIKE statement with a variable in php
$firstName = $_POST['firstName'];
$sql = "SELECT firstName FROM `colleague` WHERE `lastName`
LIKE '%{$firstName}%' LIMIT 0, 5 ";
$result = mysql_query($sql);
Why doesn't this work it does not sel开发者_如何学Goect a row and when i use
while($row = mysql_fetch_array($result)){
$output[] = $row;
echo $output;
}
This prints null and 'Array' repeated number of times
This is my android program
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("firstName",value));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
I do not receive anything in $_POST['firstName'];
There are several errors in your PHP code.
- Your SQL is injectable, which is a direct security risk. We're not fixing this here, as it is off topic.
- You are trying to echo an array, in
echo $output
. You can't echo arrays, it will just output 'Array'.
See the reviewed code below.
// ADDED QUOTES. TODO: Implement SQL injection prevention here!
$hotelName = $_POST['firstName'];
// The {brackets} here, while valid, were unnecessary.
$sql = "SELECT firstName FROM `colleague` WHERE `lastName`
LIKE '%$hotelName%' LIMIT 0, 5 ";
$result = mysql_query($sql);
// Fetch all rows, and store first names in array $output
while($row = mysql_fetch_array($result)) $output[] = $row['firstName'];
// Echo all first names with line breaks in between.
echo implode("<br/>",$output);
it does not select a row
How do you know - until you start fetching rows from the result set?
and when i use...This prints null and 'Array' repeated number of times
That rather implies it is selecting rows. If you want to see the data returned try...
print implode(',',$row);
instead of
echo $output;
You should also add some error handling, e.g.
$result = mysql_query($sql);
if (!$result) {
print mysql_error();
exit;
}
精彩评论