Search your server side MySQL Database from Node.js website

Nicholas Stepanov
3 min readMar 15, 2019

In this tutorial I will explain how to create search utility for your server side database. For the purposes of the tutorial let us assume a simple MySQL database with root user and empty password, but, of course, this database will need to be secure in a real-world application.

Our first step is to establish connection to the database from app.js file of our application:

Connect to the database

Here I have a simple Example database with a single Table and following structure:

DROP DATABASE IF EXISTS Example;
CREATE DATABASE Example;
USE Example;
DROP TABLE IF EXISTS Posting;

CREATE TABLE Posting (
ID int,
Name varchar(255),
Category varchar(16),
UserID int,
Comment varchar(255),
Price int
);

The database.query(‘USE Example’) will specify that we will search this database. For your application you could dynamically determine which database to query based on user input. This can be done using a similar approach to the one we will use to create MySQL query based on information provided by user in HTML form.

Obtaining search keywords

To get the search keyword and create a valid Database query we will need to use HTML form and specify names of input fields that we will refer to in app.js:

Create Input form for search

Now we are ready to create database queries based on the information entered. First we need to obtain the search field and category selector in app.js. Then based on this information we will construct a database query and return result back to the renderer.

Generate database queries and obtain results

The error handling here is not implemented and will just nullify the obtained results. If the query is complete without errors req.searchResult will have an array of results. Each of the array entries is in a dictionary form and resemble the Table columns. Having the results of database query in req.searchResult we are ready to pass them to our renderer and display them on the website:

Pass the results to the renderer

Now we have the searchResults accessible from our front-end and we just need to create a function that will display these results when page is loaded:

Display the results on your web page

All we have left to render the results is a <div> element with ID result as specified in the rendering function below, so create an empty one (or add some content there) <div id=”result”></div>

That’s it! Now your database can be searched from your webpage. This way you can store links, references to images or videos , map coordinates and many other useful information in your database and have it accessible on your website!

Sample search result

How does this look as a UML diagram? Our database is running on the same server as the Back-End. the Back-End and Database are exchanging information which Back-End then sends to the Web Page Front-End.

UML Diagram

--

--