Reputation: 81
I want to build a simple e-commerce site where each product is unique (each has exactly one quantity; all are stored as a separate integer) using ExpressJS and SQLite3.
My problem is with writing a query which gets all the specified products. I thought the best idea is to run query like SELECT id, name FROM products WHERE id IN (...)
, where in dots there would be a list of specific product IDs to select from.
I wanted to build such a query using a module SQLite3 with ExpressJS. The problem is it always prints undefined
instead of list of products. I do not know why is that.
const sqlite3 = require('sqlite3').verbose();
const DB_PATH = "products.db";
const db = new sqlite3.Database(DB_PATH);
db.serialize(() => {
db.run("CREATE TABLE IF NOT EXISTS products ( \
id INTEGER PRIMARY KEY, \
name TEXT NOT NULL \
)")
})
module.exports = db;
SQLite3
?const db = require('./database');
function getProductsFromCart(request) {
if (request.session.cart && request.session.cart.length > 0) {
let sql = "SELECT id, name FROM products WHERE id IN (?";
for (let i = 1; i < request.session.cart.length; i++) {
sql += ", ?";
}
sql += ")"
const params = request.session.cart;
let products = undefined;
db.all(sql, params, (err, rows) => {
if (err) {
throw err;
}
console.log(rows);
products = rows;
});
console.log(products);
return products;
}
return undefined;
}
What could be the problem? Is data binding created correctly? I tried to find solutions using StackOverflow. There was only one similar problem, but I am not sure about correctness. That's why I am asking. Thanks in advance!
Upvotes: 2
Views: 36