1

I am making a private message system and i created a php search page, I am using JQuery to pass a variable from a text field on keyUp to a PHP file called USearch.php or Username Search. Here is my code:

<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];

if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);

foreach($Term as $Key)
{
    $I = 0;
    $I++;
    if($I == 1)
    {
        $Search .= 'Username LIKE "'.$Key.'" LIMIT 0, 10 ';
    }
    else
    {
        $Search .= 'OR Username LIKE "'.$Key.'" LIMIT 0, 10 ';
    }
}

if($Result = $Connect->query($Search))
{
    while($Row = $Result->fetch_assoc())
    {
        $User = $Row['Username'];

        $USearch['S'] = $User;
    }
}
}
echo json_encode($USearch);
?>

As you can see, my code has no errors, my problem is that i am searching Users in a DB which means i am searching 1 word or string, by using this PHP code, i would have to type in the exact username for the function to return a value. My real intention was to search the string and return all similar usernames according to my input string.

4

1 回答 1

1

就像乔恩说的那样——你想%在你想让你的 SQL 有通配符的地方使用。

如果您想要名称类似于 matt 的所有值,您会这样做

WHERE name LIKE '%matt%'
于 2013-02-13T02:22:27.390 回答