Searching term with exact matching
Search the term with exact match in ‘name‘ column using the following query. The = operator finds the exact match only.
Replace it with following SQL query:
const query = `
SELECT * FROM items
WHERE name = ?
`;
Example: Below is the code example of Searching term with exact matching
Javascript
const express = require( 'express' ); const mysql = require( 'mysql2' ); const app = express(); const port = 3000; // MySQL connection const db = mysql.createConnection({ host: 'localhost' , user: 'root' , password: 'root' , database: 'mydatabase' , }); // Connect to MySQL db.connect(err => { if (err) { console.error( 'Error connecting to MySQL:' , err); } else { console.log( 'Connected to MySQL' ); } }); // Search endpoint app.get( '/search' , (req, res) => { const searchTerm = req.query.term; if (!searchTerm) { return res.status(400) .json( { error: 'Search term is required' }); } const query = ` SELECT * FROM items WHERE name = ? `; const searchValue = searchTerm; db.query(query, [searchValue, searchValue], (err, results) => { if (err) { console.error( 'Error executing search query:' , err); return res.status(500) .json( { error: 'Internal server error' }); } res.json(results); }); }); // Start the server app.listen(port, () => { console.log(`Server is running on http: //localhost:${port}`); }); |
Output:
How to Make a search function using Node Express and MYSQL
In this article, we will learn how to create a search function using Node with Express framework to search terms inside MYSQL tables.