在php文件和MySQL上使用Like函数

时间:2014-07-13 18:28:54

标签: php mysql sql-like

我有一个连接到MySQL数据库的php文件。假设从URL获取两个参数并在string参数上使用like函数。这是我的php文件:

<?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();

?>

这是php文件的URL:http://pickupfriend.fulba.com/android_project/query7.php?param=s&UserID=1。似乎函数因LIKE部分而下降。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您的查询形式应如下所示。在%

中添加''
$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%')")