How to use LIMIT and placeholders in MySQL (Node.JS)
P粉416996828
P粉416996828 2023-07-24 21:17:01
0
1
563
<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粉416996828
P粉416996828

reply all(1)
P粉141925181

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!