PHP 通过动态传递值来发布请求

我试图将两个值 name 和 company 传递给服务器,但它总是将它们作为字符串传递。


app.post('/visitors/store', (req, res) => {

const name = req.body.name; (User1)

const company = req.body.company; (Google)

con.query("INSERT INTO visitors(name, company) VALUES(`name`,`company`)", (results) => {

            res.json(results);

        });

  })

name问题出在“VALUES( , company)”行的这一部分


数据库 atm 中的结果: name = name , company = company


我需要的结果是:name = User1,company = Google


谢谢你的帮助


慕少森
浏览 77回答 2
2回答

繁花不似锦

根据您的环境,您还应该转义查询值。如果您使用 mysql,您应该可以使用以下内容:app.post('/visitors/store', (req, res) => {const name = req.body.name;const company = req.body.company;con.query("INSERT INTO visitors(name, company) VALUES(?,?)", [name, company], (results) => {    res.json(results);});或不转义:app.post('/visitors/store', (req, res) => {const name = req.body.name;const company = req.body.company;con.query(`INSERT INTO visitors(name, company) VALUES(${name}, ${company})`, (results) => {    res.json(results);});

慕后森

只需停止查询字符串并在其中包含实际变量:app.post('/visitors/store', (req, res) => {    const name = req.body.name;    const company = req.body.company;    con.query("INSERT INTO visitors(name, company) VALUES('" + name + "','" + company + "')", (results) => {        res.json(results);    });});
打开App,查看更多内容
随时随地看视频慕课网APP