How to use LIMIT and placeholders in MySQL (Node.JS)
P粉416996828
2023-07-24 21:17:01
<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>
Here's how you might handle this in your code:
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.