user2285084
user2285084

Reputation:

LIKE Clause not working due to php variable

this is my code....have tried to echo the $sql but it shows '%Search%'...but i want to use it as $Search .. plz help ...

Below is my entire code for search...

if(isset($_POST['search']))

 {

$search=$_POST['search'];

$criteria=$_POST['criteria'];

$table='alumni';

mysql_real_escape_string($search);

if($criteria=='ALL')

{

$sql="SELECT UNAME FROM `alumni` ";

$result=mysql_query($sql); 

if (!$result) {

die('Invalid query: ' . mysql_error());

}

while ($row=mysql_fetch_array($result))

{

echo"<tr><td><a>".$row['UNAME']."</a></td></tr>"; 

}

}

                                    if($criteria=='UNAME' || $criteria=='FNAME' || $criteria=='BATCH')

{

//echo $criteria;

$sql="SELECT UNAME FROM `alumni` WHERE ".$criteria." LIKE '%".$search."%'";

//echo $sql;

$result=mysql_query($sql); 

if (!$result) {

die('Invalid query: ' . mysql_error());

}

while ($row=mysql_fetch_array($result))

{

echo"<tr><td><a>".$row['UNAME']."</a></td></tr>"; 

}

}


}

?>

Upvotes: 1

Views: 83

Answers (2)

Pebbl
Pebbl

Reputation: 36075

From testing the above code there seems to be nothing wrong, if you pass search=Test you get:

SELECT UNAME FROM `alumni` WHERE FNAME LIKE '%Test%'

If you are always getting...

SELECT UNAME FROM `alumni` WHERE FNAME LIKE '%Search%'

...no matter the value you fill in your search form it would suggest there is a problem with how that form works, or how the post data is put together. The code you've posted above, whilst rather out-dated, works as you would expect from code that searches a database.

If you could post more information with regard to how this script is called or used you'll probably get a more accurate answer from someone.

Upvotes: 2

lolinthedark
lolinthedark

Reputation: 65

If you use double quotes you can put you variables in strings without closing them.

Try:

$sql="SELECT UNAME FROM `alumni` WHERE $criteria LIKE '%$search%'";

Upvotes: 0

Related Questions