1

I want to create a function that returns objects from DB where a string is contained in one of the object's columns.

This is my code:

router.get('/search-news', function (req, res) {

  var input = req.query.title; // user input
  var dynamicInput = '%'.concat(title.concat('%'));

  connection.query('SELECT * FROM news WHERE title = ?', [dynamicInput], function (err, rows) {
    console.log(err);
    res.json(rows);
  });
});

HTML:

<form action="search-news" class="form-inline right search-form" method="get">
   <input type="text" name="title" class="form-control" placeholder="Поиск..."></input>
   <input type="submit" class="btn btn-success" value="Поиск"></input>
</form>

However, this function always returns 0 records from the DB. Where is my problem?

Thank you

2 Answers 2

2

Your dynamic input seems to be appending percent signs to the beginning and end of the string.

 var dynamicInput = '%'.concat(title.concat('%'));

It is highly unlikely that any strings actually have this format, so I suspect you want like:

 connection.query('SELECT * FROM news WHERE title like ?', [dynamicInput], function (err, rows) {

However, I am not familiar with nodejs, so there may be other problems as well.

Sign up to request clarification or add additional context in comments.

Comments

0

This is the best and easiest way to do it.

 router.get('/search-news', function (req, res) {
    
      connection.query('SELECT * FROM news WHERE title = ?', [`%${req.query.title}%`], function (err, rows) {
        console.log(err);
        res.json(rows);
      });
    })

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.