Storing input data in mysql + Javascript

Asked

Viewed 244 times

0

I’m trying to store the input data below with javascript but the same is not storing:

usuers.html file

<input type="text" name="nome" id="nome">
<input type="text" name="email" id="email">


<input type="button" value="Cadastrar" onclick="clicar()"> <br><br>

<div id="res">Nome</div>

<script>
const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'willian',
    password: '123456',
    database: 'celke'

});
</script>

In the form below with the function click the same does not work and does not add the data in the database. Archive accesses.js

const mysql = require('mysql');

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'local'

});

connection.connect(function(err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }

    console.log('connected as id ' + connection.threadId);
});

connection.connect(function(err, ){
    if(err) console.error('Erro ao realizar a conxeão com BD:', + err.stack); return;
})


function clicar(){
    var  nome = window.document.getElementById('nome').value;
    var email = window.document.getElementById('email').value;

    connection.query("INSERT INTO users(nome, email) VALUES ("+nome+", "+email+")", function(err, result){
        if(!err){
            window.alert('Usuário cadastrado com sucesso!');
        }else{
            window('Erro ao cadastrar usuario!');
        }
    }); 
}

But if I test just add with the code below without function to see if the bank connection is working, the same successfully adds:

connection.query("INSERT INTO users(nome, email) VALUES ('felipe', 'felipe@felipe')", function(err, result){
    if(!err){
        console.log('Usuário cadastrado com sucesso!');
    }else{
        console.log('Erro ao cadastrar usuario!');
    }
}); 

1 answer

1

One SQL works, the other doesn’t, so just check what’s different between them.

The one that works is:

"INSERT INTO users(nome, email) VALUES ('felipe', 'felipe@felipe')"

That there are simple quotes in the values. The one that doesn’t work is:

"INSERT INTO users(nome, email) VALUES ("+nome+", "+email+")"

Without the simple quotes, then to correct simply add the quotes.

However, if you are using the mysqljs/mysql, do, view documentation:

connection.query("INSERT INTO users(nome, email) VALUES (?, ?)", [nome, email], function(err, result) {
  if (!err) {
    window.alert('Usuário cadastrado com sucesso!');
  } else {
    window('Erro ao cadastrar usuario!');
  }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.