Home > Blockchain >  Count the number of result of a sql query in mysql2
Count the number of result of a sql query in mysql2

Time:10-09

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

        })
    })

CodePudding user response:

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

  • Related