0

我正在尝试将已在表单上填写的数据存储到数据库中,但它没有存储。这段代码的目标是使用一个html文件来创建一个数据,一旦数据被输入,它就会被保存在服务器上,并从服务器端显示在表格上。我目前只能显示要显示的列名,但没有输入数据-

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");
  });
4

1 回答 1

1

你不是在检查你是否insert成功。它可能会失败。您可以使用将在语句完成或出现错误时运行的回调进行检查。

将值直接粘贴到 SQL 中会使您的代码容易受到SQL 注入、非常常见的安全问题和其他语法错误的影响。例如,如果您的消息包含 a ",它将破坏insert.

您应该改用占位符。

把它们放在一起,就是这样。

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('/'); 
    }
  }
);

您的代码可以通过使用来简化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>");
});

这更简单,更有效。db.all如果您有很多用户,将一次性将所有行放入内存中,可能会使用大量内存。db.each一次拿一个。

于 2019-10-03T04:44:54.013 回答