1

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.

1
  • LIMIT argument must be numeric parameter LITERALLY. So wrapping quotes are treated as its part - with according error. dbfiddle.uk/… Commented Sep 25, 2020 at 12:21

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.