Search code examples
mysqlnode.jsexpresssql-limit

Can't Escape Limit Value in Mysql & Express Node JS


I'm developing an API with Node.js (+Express JS) and MySQL. I can't escape or add custom limit value to my query. Here is my route;

app.post('/api/v1/fetch/limitedArticles/:limit', (req, res,) => {

    const limitValue = req.params.limit;

    let query = "SELECT article_id, article_name, article_image, article_url FROM ?? ORDER BY article_id DESC LIMIT ?";

    mysqlDB.query(query, ['app_articles', limitValue], function (mysqlError, mysqlRes) {
        if(mysqlError){
            return res.status(500).send({message: "error_server_db"});
        }else if(mysqlRes.length<1){
            return res.status(404).send({message: "warning_empty_list"});
        }else{
            //All good
            return res.status(200).send(mysqlRes);
        }
        throw mysqlError;

    })
});

I request as;

{{api_base_url}}/api/v1/fetch/limitedArticles/2

And I get this error;

{
"message": {
    "code": "ER_PARSE_ERROR",
    "errno": 1064,
    "sqlMessage": "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''2'' at line 1",
    "sqlState": "42000",
    "index": 0,
    "sql": "SELECT article_id, article_name, article_image, article_url FROM `app_articles` ORDER BY article_id DESC LIMIT '2'"
}

}

If I remove parameter value and type "2" to my limit value (e.g LIMIT 2), it works. But it doesn't work as I showed.


Solution

  • limitValue is a string - you should convert it to a number so it can be used in the limit clause:

    const limitValue = Number(req.params.limit);