1

I am running a search bar to search through user created levels in a Unity game, however the code is returning really weird results. Sometimes it is returning the right levels back, sometimes only some that match the search string but not all or sometimes it doesn't return anything. I am pretty sure the bug is somewhere within the PHP code because I am logging the search string as it is sent to the PHP script and then logging the string results immediately. Please help, I am pretty inexperienced with PHP and SQL. I hope it's not just a stupid syntax error, if it is sorry for wasting your time.

A screenshot of the entire table - https://gyazo.com/b3d00ec968820f5fa6ff23681af3e27f

If I search nothing in the searchbar they are all returned. - https://gyazo.com/af40746d932ee79fc131ef90508bd4b7

If I search 'tester' which is found in the names of two levels I only get one result - https://gyazo.com/cec247e04c21c0b3eaafa791e2204436

Or if I search '1' which is found in several level names I only get two results, not including 'tester1' which was the last result - https://gyazo.com/1558c6b7db80597476186d4387ae5daf

And if I search 'alex' like is found in the name of the creator 'alexander' it returns nothing - https://gyazo.com/43fcf76214fd35482787bb3644442824

However in the debug log it shows that if I search using something like 'alex' it is returning a string '' but if I search with a search term not found in the table like 'Orange' it returns 'No user maps found' as it should - https://gyazo.com/79f44116378f4b50f3b01efd3378d546

$search = $_POST["Search"];

//PDO
$stmt = $conn->prepare("SELECT * FROM metadata WHERE levelname 
LIKE concat('%',:search,'%') OR username LIKE concat ('%',:search,'%')"); 

$stmt->bindValue(':search', $search);
$stmt->execute();   
$row = $stmt->fetch();  

if($row != null)    
{
    //Show data for each row
    $data = $stmt->fetchAll();
    foreach($data as $row)
    {
            echo $row["username"]."@".$row["rating"]."@".$row["levelname"]."@".$row["id"]."@".$row["numRatings"].",";
    }
}
else
{
    echo "No user maps found";
}
  • 4
    You need to put the `%` characters into your placeholder - e.g. `$stmt->bindValue(':search', "%" . $search . "%");` rather than your SQL string. – CD001 May 03 '19 at 13:58
  • Thank you but this is still returning the same result – weirdybeardyman May 03 '19 at 14:23
  • I fixed it, it was due to fetching the results and then fetching all later on, not sure why this works better but it does- ```php $data = $stmt->fetchAll(); #if($row1 != null) if($data != null) { //Show data for each row #$data = $stmt->fetchAll(); foreach($data as $row) { echo $row["username"]."@".$row["rating"]."@".$row["levelname"]."@".$row["id"]."@".$row["numRatings"].","; } }``` – weirdybeardyman May 04 '19 at 13:33

0 Answers0