Search code examples
phpmysqlsql-like

Using Like function on php file and MySQL


I have a php file that is connected to a MySQL database. It is suppose to get two parameters from the URL and using a like function on the parameter that is string. This is my php file:

<?php

mysql_connect("mysql.1freehosting.com","u948577195_uname","p7CraCuRAw");

mysql_select_db("u948577195_dbnam");

$param = $_GET['param'];
$UserID = $_GET['UserID'];

$sql=mysql_query("SELECT        UserID, UserName, DisplayName
FROM          User
WHERE       (UserID <> '$UserID') and (UserID NOT IN
                             (SELECT        UserID1 AS UserID
                               FROM            Friend
                               WHERE        (UserID2 = '$UserID')
                               UNION ALL
                               SELECT        UserID2 AS UserID
                               FROM            Friend AS Friend_1
                               WHERE        (UserID1 = '$UserID'))) AND( (UserName LIKE %'$param'%) OR
                            (DisplayName LIKE %'$param'%))");

while($row=mysql_fetch_assoc($sql))

$output[]=$row;

print(json_encode($output));

mysql_close();

?>

This is the URL for the php file: http://pickupfriend.fulba.com/android_project/query7.php?param=s&UserID=1. It seems that the function falls because of the LIKE part. How can I solve that?


Solution

  • Your query formation should be like below. Include the % inside ''

    $sql=mysql_query("SELECT UserID, 
    UserName, 
    DisplayName
    FROM User
    WHERE UserID <> '$UserID'
    and UserID NOT IN (
    SELECT UserID1 AS UserID
    FROM Friend
    WHERE UserID2 = '$UserID'
    UNION ALL
    SELECT  UserID2 
    FROM Friend 
    WHERE UserID1 = '$UserID'
    ) 
    AND (UserName LIKE '%$param%'
    OR DisplayName LIKE '%$param%')")