0

I am trying to do a search on my database where it returns results based on exact surnames and first names with the initial of the name entered in an input box. For instance, if the user enters Simon Burns it will return all users with the initial S for the first name and Burns for the Surname. Here is my code.

Sorry if this has been covered before but I cannot find a simple answer that works.

$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
$surname = filter_input(INPUT_POST, 'surname', FILTER_SANITIZE_STRING);

$prep_query = "SELECT id, firstname, surname, profilepic, Gender, StartYear, EndYear, CircaStart, CircaEnd, JnrHouse, SnrHouse
                   FROM people WHERE firstname LIKE ? AND surname = ?";
$namecheckresult = $connection->prepare($prep_query);

// Return all matches wether registered on not
if ($namecheckresult) 
    {
    $initial = $firstname[0];   
    $namecheckresult->bind_param( 'ss',  $initial . '%', $surname);
    $namecheckresult->execute();
    $namecheckresult->store_result();
    $namecheckresult->bind_result($id, $first, $last, $ProfilePic, $Gender, $StartYear, $EndYear, $CircaStart, $CircaEnd, $JnrHouse, $SnrHouse);  
J. Doe
  • 1,291
  • 2
  • 10
  • 19

2 Answers2

-1

You have mixed up your 2 parameters

Change it to

$p1 = '%'.$initial;
$namecheckresult->bind_param( 'ss',  $p1 , $surname);

Or you may want to put the % on the front and back of $initial like this

$p1 = "%$initial%";
$namecheckresult->bind_param( 'ss',  $p1 , $surname);
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
-2

I have now worked out the answer.

changing $initial = $firstname[0];

to

$initial = "%$firstname[0]%";

works.

Hope this helps others.

  • Well, actually as written on http://php.net/manual/de/mysqli-stmt.bind-param.php the variable has to be a reference. So you may not build a string together in the argument section. A change of `$initial = $firstname[0]; $namecheckresult->bind_param( 'ss', $initial . '%', $surname);` to `$initial = $firstname[0].'%'; $namecheckresult->bind_param( 'ss', $initial, $surname);` should do the work ... – Max Senft Mar 18 '18 at 09:08
  • I tried the above you posted and that still throws an error. My solution does not and works. – Steve Beard Mar 18 '18 at 09:19