Angular 17 Search Autocomplete with Php and MySql

Raffaele Ianniello
5 min readJan 1, 2024

--

The search bar has now become a fundamental element of all websites, because without it it would be impossible to search for content according to our needs.

In this article we will try to understand in broad terms how to structure a search bar within an already existing Angular project.

Now we won’t write an entire project but we will explain the fundamental points to take into consideration and everything according to my personal experience, clearly you can organize it as you want.

We definitely start with the input found in app.component.html, so we can work our way backwards to other modules.

<input type="search"
class="form-control rounded-5"
formControlName="search"
placeholder="Search User ..."
(keyup)="sendData($event)" />

The fundamental part that interests us is certainly (keyup)=”sendData($event)” , which as you already know, the sendData() function is found inside app.component.ts and is used to transfer everything that is typed on the keyboard to search for what we are writing on our server. So there will be http calls and then you need to organize app.config.ts that can collect them with the call to the angular module

import { HttpClientModule } from ‘@angular/common/http’

Also I created a User interface in interface/user.ts

export interface User {
id: number;
username: string;
name: string;
email: string;
}

This interface is used to collect, in the right way, the data coming from the MySql server

I also created a service services/users.service.ts, so I can make an Http call to the server.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { User } from "../interface/user";

@Injectable({
providedIn: 'root'
})
export class UserService {

public urlPhp : string = "/server/api_users";

constructor( private http: HttpClient) { }

searchUser( params : any){

return this.http.post<User[]>(this.urlPhp, JSON.stringify(params))
.pipe(map(result => {
return result
}));
}
}

As you can see, the searchUser function is passed parameters in json format from the sendData() function in app.component.ts, which should look like this:

  sendData(event: any) {

if (event.target.value === "") {
this.users = [];
this.ifSearch = false;
return;
}

this.requestUser = {
action: 'search_user',
str: event.target.value
};

this.userService.searchUser(this.requestUser).subscribe(result => {

if (result.length > 0) {
this.ifSearch = true;
this.users = result;
//console.log(this.users)
} else {
this.ifSearch = true;
this.users = [{ id: 0, username:"", email:"", name:"Sorry, nothing found, try searching again" }];
}

});
}

Let’s explain this code a little:

event.target.value would be the string that i am typing into the input, now if this string is empty the users array must remain empty, it must not display anything, the ifSearch variable serves precisely to not display the dropdown box with the list of users, and therefore with return there will be an exit from the function.

this.requestUser is the json format that arrives at the php file, in action we find the name of the function that is called inside the php file /server/api_users.php, str the string I’m looking for. Now by calling the userService.searchUser function with the result variable we read what is returned from the server and in the first if part we check if there is any data and assign it to the users array so that it will be read in app.component.html, if instead the result variable does not contain data, the users array will have as its only element “Sorry, nothing found”

Now in the html there will be a for loop that lists the users array.

@if (ifSearch) {
<li class='abb abc abd abf' >
<ul class='abh' slimScroll [options]="opts" [scrollEvents]="scrollEvents">
@for (user of users; track user.id ) {
<a (click)="onSelectUser(user)">
{{user.username}} {{user.name}} {{user.email}}
</a>
<hr class="abe">
}
</ul>
</li>
}

by clicking on the element in the dropdown box, the onSelectUser() function will be called which will do nothing but display the name in the console or could be used for future developments.

Now let’s move on to the server side, dealing with the server/api_user.php file.

To be able to talk about Php/MySql, I imagine that you will already have a server installed on your computer so that you can satisfy all the requests coming from the Angular project. If you don’t have it, take a look around the internet where you will find many tutorials on how to do it.

Given this, and we take it for granted that you have installed a Php/MySql server on your PC, let’s analyze the php file which will take care of taking the data from a table and returning it to the Angular project.

$request = json_decode(file_get_contents("PHP://input"));
$action = $request->action;

To make sure that everything works, at the beginning of the api_users.php file there must be these two lines of code where we have to pause a bit to explain what they mean. The $request variable decodes the json call coming from sendData() this.requestUser and stores it.

the php $action variable stores the action variable, coming from the this.requestUser json str is the string I’m looking for that is used in the search function.

Let’s move on to the rest of the php file.

switch ($action) {

case "search_user":
search_user($mysqli, $request);
break;
}

function search_user( $mysqli, $request ) {

$dati = array();
$cerca = $mysqli->real_escape_string($request->str);

$search = "%$cerca%";
$sql = "SELECT * FROM users WHERE concat(username,name) LIKE ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0 ) {
$n = 0;
while ($row = $result->fetch_assoc()) {
$dati[$n]['id'] = $row['id'];
$dati[$n]['username'] = $row['username'];
$dati[$n]['name'] = $row['name'];
$dati[$n]['email'] = $row['email'];
$n++;
}
}

echo json_encode($dati);
$mysqli->close();

}

with a switch control on the $action variable, we ensure that the search_user function is called where both the database parameters and the $request json are passed to it. Inside the function the variable $search is used where the string I am looking for is stored, which I typed in the input. Then a search is done on the users table, if something is found it is stored in the $data array which is returned in json format by the json_encode function of php, and this is where php’s task ends.

And this is all, I hope I have been of help, if there are any questions or clarifications write to me or comment, I will always answer you as soon as possible.

Originally published on https://babbler.eu

the entire project can be found on GitHub at the link:

https://github.com/babbler-eu/angular-search-autocomplete

--

--