Count the number of result of a sql query in mysql2

Issue

I’m actually trying to code an API and I have to count the number of result of MySQL request. I’m using ExpressJS and MySQL2 libraries and here is my code:

    app.get('/:token/checkUser/:username', function(req, res) {
        db.query(('SELECT * FROM users WHERE user_username LIKE '+req.params.username), function(err, result) {
            
            if (err) throw err;
           //Count the number of results

        })
    })

Solution

It is simple you need change two part in your code one of is use count function to get size of result for example:

db.query(('SELECT COUNT(*) FROM users WHERE user_username LIKE '+req.params.username), function(err, result) {
            
            if (err) throw err;
           //Count the number of results

        });

and last one is prevent sql injection for example:

db.query(('SELECT COUNT(*) FROM ?? WHERE ? LIKE'),['users','user_username',req.params.username], function(err, result) {
            
            if (err) throw err;
           //Count the number of results

        });

for more information about sql injection click this link please read mysql documentation

Answered By – Ali Azmoodeh

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published