How to save a value in mysql with express

0

I'm doing a login but I have a problem that I can not save the data in mysql. For the register I made a form with a method post. With express create the connection that is this:

const mysql= require("mysql");

module.exports=()=>{
    return mysql.createConnection({
        host:"localhost",
        user:"pedri",
        password:"cocoypaco2",
        port:3306,
        database:"users"    
    });
};

This is the route of the form:

routes.post("/register/newuser",(req,res)=>{
    controller.register
});

And I made a separate folder to put the mysql data modifiers. In this case called controller.

The controller.register is this:

const controller= {};
const mysql= require("../mysql/mysql");

controller.register=(req,res)=>{
    var inputname= req.body.inputname;
    var inputsurname= req.body.inputsurname;
    var inputemail= req.body.inputemail;
    var inputpassword = req.body.inputpassword;

    mysql.connection((req, res)=>{
        connection.query("INSERT INTO user (name, surname, password, email)
        VALUES (inputname, inputsurname, inputpassword, inputemailf)");
    })
};

module.exports=controller;

Does anyone know by chance that I am doing wrong? Thank you very much.

    
asked by Pedro Danderfer 17.11.2018 в 16:27
source

1 answer

0
mysql.connection( // 1
    (req, res)=>{ // 2
        connection.query("INSERT INTO user (name, surname, password, email)
        VALUES (inputname, inputsurname, inputpassword, inputemailf)"); // 3
})
  • You are already exporting a connection from the connection.js file, you should only use it in your controller and not try to create another one.
  • The callback function that receives the request and response parameters is used as a handler of a request to an Express route, that code does not make sense.
  • The arguments you are passing to the insert are strings of characters, and they should be references to the variables you defined just above.
  • One way to do it is:

    connection.query(
        "INSERT INTO user (name, surname, password, email) VALUES (?, ?, ?, ?)",
        [inputname, inputsurname, inputpassword, inputemailf],
        function (error, results, fields) {
            if (error) { /* haz algo */ }
            if (results) { /* haz otra cosa */ }
        }
    )
    

    Documentation

        
    answered by 18.11.2018 в 23:26