Pedro
Pedro

Reputation: 23

Preparing statement with input in Nodejs and Sqlite3

I'm trying to read from my database using the sqlite3 package in NodeJS. In the code I have:

 var sqlite = require('sqlite3');
 var db = new sqlite.Database('myDatabase.db');

 var someUserInput = 'Some given id by the user';

 db.all(
     'SELECT * FROM MyTable WHERE userId="' + someUserInput + '"',
     function(err, rows) { /* Do something here */});

Instead of directly adding the user input, I would like to be able to prepare the statement properly, in order to avoid any malicious input from the user.

I have tried:

 db.prepare('SELECT * FROM MyTable WHERE userId=?', someUserInput).sql

But that still gives me:

'SELECT * FROM MyTable WHERE userId=?'

With no replacement from the input.

Thanks!

Upvotes: 2

Views: 1680

Answers (1)

jkeeler
jkeeler

Reputation: 1008

I think you almost had it with your db.all call. Try passing your user value as a parameter:

db.all(
     'SELECT * FROM MyTable WHERE userId=?',
     someUserInput,
     function(err, rows) { /* Do something here */});

Source: https://github.com/mapbox/node-sqlite3/wiki/API#databaseallsql-param--callback

Upvotes: 1

Related Questions