'send a radio button value to the database
I have created form to apply values then insert to the table. I need help to send a radio button value to the database
nodejs /ejs file
<label class="container" >5
<input type="radio" name="_rate" id="_rate" value="5" required >
<span class="checkmark"></span>
</label>
<label class="container">3
<input type="radio" name="_rate" id="_rate" value="3">
<span class="checkmark"></span>
</label>
<label class="container">1
<input type="radio" name="_rate" id="_rate" value="1">
<span class="checkmark"></span>
</label>
app.js
var _rate= req.body._rate;
var sql = `INSERT INTO [Test2] (rate) VALUES ('${_rate}')`;
the value always in table shows null !!
Solution 1:[1]
What type of data is expected in your database field?
In any case, please use prepared statements to avoid type errors like :INSERT INTO [Test2] (rate) VALUES (?)
Solution 2:[2]
Ejs:
<form method="POST" action="/">
<label class="container" >5
<input type="radio" name="_rate" id="_rate" value="5" required >
<span class="checkmark"></span>
</label>
<label class="container">3
<input type="radio" name="_rate" id="_rate" value="3">
<span class="checkmark"></span>
</label>
<label class="container">1
<input type="radio" name="_rate" id="_rate" value="1">
<span class="checkmark"></span>
</label>
</form>
Nodejs:
const express = require('express');
const mysql = require('mysql2');
const app = express();
const db = mysql.createConnection({
host: //'localhost' or you hostname,
user: //'root' or your username,
password: //yourpassword,
database: //'database name',
})
app.post("/", async (req, res)=>{
const _rate = req.body._rate
await db.query("INSERT INTO Test2 (rate) VALUES (`${_rate}`)", (err, result) {
if (err) {
//Handle error
} else {
//Do whatever you want with `result`
}
})
app.listen(3000, ()=>{
console.log('Server started working on port 3000')
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Michaƫl |
| Solution 2 | jkalandarov |
