Skip to content
Advertisement

How to make a workable SQL request for NodeJS file?

I have a js file to work with my local database, and a POST request is not working like it should – if I enter a specific row, it returns a correct result, but I need it to get the variable from post data. This type of entering query doesn’t work 🙁

app.post("/search", (req, res, next) => {

    var post_data = req.body; // get post body
    var course_search = post_data.search; // get field 'search' from post data

    //var query = 'SELECT * FROM courses WHERE title LIKE "%Java%"';
    var query = 'SELECT * FROM courses WHERE title LIKE "%' + course_search + '%"';

    con.query(query, function (error, result, fields) {
        con.on('error', function (err) {
            console.log('[MYSQL]ERROR', err)
        });

        if (result && result.length) {
            res.end(JSON.stringify(result));
        } else {
            res.end(JSON.stringify('There is nothing to show on your request'));
        }
    });
});

Advertisement

Answer

You can try to use the “Prepared Statements”. As an example using your code:

app.post("/search", (req, res, next) => {

var post_data = req.body; // get post body
var course_search = post_data.search; // get field 'search' from post data

//var query = 'SELECT * FROM courses WHERE title LIKE "%Java%"';
var query = 'SELECT * FROM courses WHERE title LIKE "%?%"';

con.query(query, [course_search], function (error, result, fields) {
    con.on('error', function (err) {
        console.log('[MYSQL]ERROR', err)
    });

    if (result && result.length) {
        res.end(JSON.stringify(result));
    } else {
        res.end(JSON.stringify('There is nothing to show on your request'));
    }
  });
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement