0

i'm working on an electron app for school. When i want to insert data in my sqlite database with nodejs, it fill the database with null values. I'm getting the data from input value.

database image: https://i.stack.imgur.com/8FMmE.png

Here is my code:

<!DOCTYPE html>
<html>
  <head>
    <title>Tableau de patient</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <h1>Ajouter un patient</h1>
    <input type="text" name="nom" placeholder="nom" id="lastname">
    <input type="text" name="prenom" placeholder="prenom" id="name">
    <br>
    <input type="text" name="age" placeholder="age" id="year">
    <input type="text" name="sexe" placeholder="sexe" id="genre">
    <br>
    <button type="button" name="sendData" id="send">Creer</button>
    <script>
    const sqlite3 = require('sqlite3').verbose();

    // open the database
    let db = new sqlite3.Database('./database.db', sqlite3.OPEN_READWRITE, (err) => {
    if (err) {
      console.error(err.message);
    }
    console.log('Connected to the database.');
    });

      var Inom = document.querySelector('#lastname').value;
      var Iprenom = document.querySelector('#name').value;
      var Iage = document.querySelector('#year').value;
      var Isexe = document.querySelector('#genre').value;

      var parameters = [Inom, Iprenom, Iage, Isexe];
      var sql = 'INSERT INTO patient(nom, prenom, age, sexe) VALUES (?, ?, ?, ?)';

      var btn = document.getElementById("send")
      btn.addEventListener('click', function(){
        console.log("ok")
        db.run(sql, [parameters],function(err) {
          if (err) {
            console.error(err.message);
          }
        })
        db.close((err) => {
        if (err) {
          console.error(err.message);
        }
        console.log('Close the database connection.');
        });
      })
    </script>
  </body>
</html>

I don't where the issue is from. Thanks for help :)

Lucas B
  • 1
  • 5

1 Answers1

1

Dred, Your querySelector value is outside of clickevent. You cannot access elements while page loading Put your block in click event

  var btn = document.getElementById("send")
  btn.addEventListener('click', function(){
    var Inom = document.querySelector('#lastname').value;
    var Iprenom = document.querySelector('#name').value;
    var Iage = document.querySelector('#year').value;
    var Isexe = document.querySelector('#genre').value;

    var parameters = [Inom, Iprenom, Iage, Isexe];
    var sql = 'INSERT INTO patient(nom, prenom, age, sexe) VALUES (?, ?, ?, ?)';
    console.log("ok")
    db.run(sql, [parameters],function(err) {
      if (err) {
        console.error(err.message);
      }
    })
    db.close((err) => {
    if (err) {
      console.error(err.message);
    }
    console.log('Close the database connection.');
    });
  })
cancmrt
  • 139
  • 3