简体   繁体   中英

How to use like query in mysql using nodejs

I have been trying to use like query on MySQL but it won't match the pattern with database and only works when the exact keyword is given(% sign doesn't work)

I have tried Concat method, using backslash for special characters,+ symbol and every other approach I can find but still, it isn't working

connection.query('SELECT * FROM job where domainname like ?', '%' + request.body.domain + '%' ,function(error, results){
            response.render('./results',{rows:results});    

    });
and on front end part
  <tbody>
    <% for(var i=0; i < rows.length; i++) { %>
   <tr>
     <td><%= i %></td>
     <td><%= rows[i].companyname %></td>
     <td><%= rows[i].domainname %></td>
   </tr>
<% } %>

Error: Cannot read property 'length' of undefined it works if I don't use % and don't try pattern matching and then shows the results.

Pushkar, welcome to StackOverflow. I might be able to shed a little light on your query. In my experience the 'LIKE' operator in MySQL works as follows:

  • % at the beginning means ignore character before the match. 'qweradsf zxcv
  • % at the end means ignore characters after the match. ' qwer asdfzxcv'
  • %% means the match can be in the middle of a string. 'qwer asdf zxcv'

The length error is due to 'rows' having no value. A good defensive programming habit is to never trust that data from a 3rd part is populated. Just like we never trust user input, never trust 3rd party data. In this case, wrap the SQL select with a check. If 'rows' has no values, do not try to render the the tbody.

Back to the SQL query; try hard coding all the values as string literals. See if the query as formulated return any values. Then pull it apart into the parameterized version.

try to keep the values in array

connection.query('SELECT * FROM job where domainname like ?', ['%' + request.body.domain + '%'] ,function(error, results){
        response.render('./results',{rows:results});    

});

print error and results if it is not working

for more info goto - https://www.npmjs.com/package/mysql#performing-queries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM