INSERT INTO cannot add value received from the form.

Asked 1 years ago, Updated 1 years ago, 49 views

I would like to add the data I entered with the form tag using Node to the Mysql database, but no matter how hard I try, the characters I entered are not added and are not displayed on the screen.If you don't mind, I would appreciate your help.

OS:Windows 10
node —version 1.0.0
mysql:version 2.18.1
ejs:version 2.18.i

server.js

let express=require("express")
const mysql=require('mysql')

let http=require('http')
letapp=express()
let server = http.createServer(app)

app.use(express.static('public')))
app.use(express.urlencoded({extended:true}))


const connection=mysql.createConnection({//Connect to database)
    host: 'localhost',
    user: 'root',
    password:', 
    database: 'mydb'
});

app.get('/',(req,res)=>{
    connection.query('SELECT* FROM zatu', (error, results) = > {
        console.log(results)
           res.render('top.ejs', {zatu:results})
    })

})

app.get('/new',(req,res)=>{
    res.render('new.ejs')
})

app.post('/create',(req,res)=>{// Where is this problem?
    console.log (req.body.zatuName, req.body.zatuContent)

    connection.query('INSERT INTO zatu(title) VALUES(?), [req.body.zatuName], // This action is not working
    (error, results) = > {
        connection.query('SELECT* FROM zatu', (error, results) = > {
            res.render('top.ejs', {zatu:results})
        })
    })
})

app.listen(process.env.PORT,()=>{
    console.log ("HelloWorld")
})

top.ejs

<div class="item-form-wrapper">
      <form action="/create" method="POST">
        <input class="input" type="text" name="zatuName" placeholder="Title of miscellaneous studies"><!--name attribute specified -->
        <textarea class="textarea" placeholder="small description" name="zatutitle"></textarea><!--- I can't get a name in textarea for some reason-->
        <input type="submit" class="Button is-success is-rounded" value="Post">
      </form>
  </div>

mysql node.js

2022-09-30 17:07

1 Answers

After replacing the req.body~ received in form with another variable and rewriting the query's VALUES as above, I was able to add it in INSERT.

app.post('/create', (req,res)=>{
    var title_db = req.body.zatuTitle
    var content_db = req.body.zatuarea
    connection.query('INSERT INTO zatu(title, content) VALUES('+title_db+', '+'"+content_db+')', 
        (error, results) = > {
            res.redirect('/')
            console.log(error)
    })
})


2022-09-30 17:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.