Search code examples
node.jssqlitenode-sqlite3

input value not storing in database


I am trying to store data that has been filled out on form onto a database but it isn't storing. The goal of this code is use a html file to make a from and once the data has been input, then it will be saved on the server and be displayed on table from the server side. I am currently only able to get the column names to be displayed but no input data-

var express = require('express');
var bodyParser = require("body-parser");
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database('myDBnaima3');

var app = express();

app.use(express.static('public_html'));

app.use(bodyParser.urlencoded({
   extended: false
 }));

app.post('/Contact', function (request, response, next) {
 let name = request.body.Name;
 let email = request.body.Email;
 let message = request.body.Message;

 //db.run('CREATE TABLE IF NOT EXISTS users (id INTEGER UNIQUE PRIMARY KEY NOT NULL, name TEXT NOT NULL, email TEXT NOT NULL);');
 var statement = db.run(`INSERT INTO users (name, email, message) VALUES    ("${name}","${email}","${message}");`);
 console.log("Information Entered Succesfully!");
 res.status(200).redirect('/'); 
});

app.get('/Contact', function (request, response, next) {
  db.all('SELECT * FROM users;', function (error, rows) {
     response.write(`<table border=1>`);
     response.write("<tr>");
     response.write(`<th>ID</th>`);
     response.write(`<th>Name</th>`);
     response.write(`<th>Message</th>`);
     response.write("</tr>");

     rows.forEach(row => {
         response.write("<tr>");
         response.write(`<td>${row["name"]}</td>`);
         response.write(`<td>${row["email"]}</td>`);
         response.write(`<td>${row["message"]}</td>`);
         response.write("</tr>");
     });
     response.write("</table>");
   });
 }); 

 app.listen(3000, function () {
   console.log("Web server running at: http://localhost:3000 NAIMA IS HERE AGAIN!!!!");
   console.log("Type Ctrl+C to shut down the web server");
  });

Solution

  • You're not checking if your insert succeeds. It could be failing. You can check with a callback that will be run when the statement finishes, or when there's an error.

    Pasting values straight into your SQL makes your code vulnerable to SQL Injection, a very common security problem, and other syntax errors. If, for example, your message contains a " it will break the insert.

    You should instead use placeholders.

    Putting them together, it's something like this.

    db.run(
      "INSERT INTO users (name, email, message) VALUES ($name,$email,$message)",
      { $name: name, $email: email, $message: message },
      (error) => {
        if( error ) {
          console.log(`Insert failed: ${error}`);
          res.status(500);
        }
        else {
          console.log("Information Entered Succesfully!");
          res.status(200).redirect('/'); 
        }
      }
    );
    

    Your code can be simplified by using db.each.

    app.get('/Contact', function(request, response, next) {
      response.write(`<table border=1>`);
      response.write("<tr>");
      response.write(`<th>ID</th>`);
      response.write(`<th>Name</th>`);
      response.write(`<th>Message</th>`);
      response.write("</tr>");
      db.each('SELECT * FROM users;', function(error, row) {
        response.write("<tr>");
        response.write(`<td>${row["name"]}</td>`);
        response.write(`<td>${row["email"]}</td>`);
        response.write(`<td>${row["message"]}</td>`);
        response.write("</tr>");
      });
      response.write("</table>");
    });
    

    This is simpler and more efficient. db.all will slurp all the rows into memory at once potentially using a lot of memory if you have a lot of users. db.each will fetch them one at a time.