Home  >  Q&A  >  body text

How to use LIMIT and placeholders in MySQL (Node.JS)

<p>I'm trying to execute a query with placeholders using Node.js and MySQL. However, the LIMIT placeholder doesn't seem to work because the value after it should be without quotes. This is my query: </p> <pre class="brush:php;toolbar:false;">SELECT userName, clicks FROM users ORDER BY clicks DESC LIMIT ?</pre> <p>How do I get the behavior I want using placeholders, is this possible? The following is the complete code statement, where data.topUsersCount is an integer value: </p> <pre class="brush:php;toolbar:false;">con.query("SELECT userName, clicks FROM users ORDER BY clicks DESC LIMIT ?", [data.topUsersCount], (err, topUsersData) => { // Handle data });</pre> <p>I also tried using the double placeholder "??" but it didn't work either. </p>
P粉416996828P粉416996828425 days ago564

reply all(1)I'll reply

  • P粉141925181

    P粉1419251812023-07-25 18:20:58

    Here's how you might handle this in your code:

    if (Number.isInteger(data.topUsersCount)) {
      let queryString = "SELECT userName, clicks FROM users ORDER BY clicks DESC LIMIT " + data.topUsersCount;
    
      con.query(queryString, (err, topUsersData) => {
        // Handle data
      });
    } else {
      // Handle error
      console.log("Invalid limit value");
    }
    

    In the above code, use Number.isInteger(data.topUsersCount) to check whether data.topUsersCount is a safe integer before incorporating it into the query string. This is critical to preventing SQL injection attacks.

    reply
    0
  • Cancelreply