I'm relatively new to using node.js and sqlite3. I'm trying to check to see if a users name and password entered thorough a form matches ones saved in an sqlite3 db. I want to raise an error if the username/password entered doesn't match those in the db, otherwise send the user to another page.
Relevant form:
<form action="/account" method="post">
<div class="form-group">
<label for="user">Name:</label>
<input type="text" id="user" name="name">
</div>
<div class="form-group">
<label for="pass">Password:</label>
<input type="password" id="pass" name="password">
</div>
<button type="submit">Submit</button>
Database create and comparison to form:
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
db.run("CREATE TABLE Accounts (id INTEGER, username TEXT, password TEXT, fullname TEXT");
db.run(`INSERT INTO Accounts VALUES (1, "bob", "password", "Bob Bobson")`);
});
});
db.close();
app.get('/account', function (req, res) {
db.all('SELECT * FROM Accounts', function(err, rows){
rows.forEach(function (row){
if (row.username == req.body.user)
//go to success page
if (row.username != req.body.usr)
//list error
});
res.send();
});
});
It is not wise to run a query and retrieve all the rows from accounts table. If the table is too big it will take a lot of time. It's better to do a "get" query with parameters and retrieve the specific row if it exists. If it exists the row parameter in the function callback will NOT be undefined.
db.get("SELECT * from ACCOUNTS where username=? and password=?",
[req.body.user,req.body.password],function(err,row){
if(typeof row!=='undefined' && row!=null){ console.log('user exists'); }
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.