0

So I'm building a little Search Engine to work with a database I've created and I want this search engine to return multiple results when you search. For example if you put in Jo it would return both John and Joe. This is what I've built so far:

$query = mysqli_query($con,"SELECT * FROM users WHERE name LIKE '%" . $searchquery . "%' ");
  $results = mysqli_fetch_array($query);
  return $results;

The problem I'm having is I only get one result, Joe because of alphabetical order, but I want it to return both Joe John and whatever other results. I know I'm missing something or doing something wrong and I would appreciate any guidance! Cheers!

3
  • 1
    Probably because you're fetching only one(first) row from the result set and returning it immediately. By seeing the return statement I'm assuming you have that block of code inside a function. Commented Jan 15, 2017 at 0:50
  • Other than the connecting to the database, that's the only other code inside the function. I'm using return as it's via AMFPHP. Commented Jan 15, 2017 at 0:54
  • I've given an answer below. Hopefully this will resolve your issue. Commented Jan 15, 2017 at 1:03

1 Answer 1

1

From OP's comment,

Other than the connecting to the database, that's the only other code inside the function. I'm using return as it's via AMFPHP.

Since you're using the above code block inside a function, the problem appears because of the mysqli_fetch_array(...); and the return statement. You're fetching only one(first) row from the result set and returning it immediately.

The solution is, create an empty create array and loop through the result set using while() loop. And in each iteration of the loop, fetch a row from the result set and push it in the array. Finally at the end of the function, simply return that array.

So your code should be like this:

$query = mysqli_query($con,"SELECT * FROM users WHERE name LIKE '%" . $searchquery . "%' ");

$resultArr = array();
while($results = mysqli_fetch_array($query)){
    $resultArr[] = $results;
}
return $resultArr;

Sidenote: If you want to see the complete result array structure, do var_dump($resultArr);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.