如何在MySQL查询中传递Javascript变量

时间:2017-09-08 16:56:45

标签: javascript jquery mysql node.js

我做了一些研究,我得到了相互矛盾的答案,所以就这样吧。您是否必须首先将JS变量传递给PHP,还是可以将它们直接插入MySQL表?我在node.js中运行了这个,谢谢!

var part = [];
var des = [];
var price = [];
var request = require('request');
var cheerio = require('cheerio');
var mysql = require('mysql');

var con = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "",
  database: "parts"
});

request('URL', function(error, response, body) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(body);
        getPartNumber();
        getDescription();
        getPrice();
        con.connect(function(err) {
        if (err) throw err;
        for (var i = 0; i<part.length; i++){
            var sql = "INSERT INTO data_9_17 (partNumber, description, price) VALUES (part[i], des[i], price[i])";
            con.query(sql, function (err, result) {
                if (err) throw err;
                console.log("1 record inserted, ID: " + result.insertId);
            });
        }
});

function getPartNumber() {
$("input[name = 'sku']").each(function() { part.push($(this).val()) });
}

function getDescription() {
$(".ellipsis_text").each(function() { des.push($(this).text()) });
}

function getPrice() {
$(".sellprice, .dbl").each(function() { price.push($(this).text()) });
}
}
});

3 个答案:

答案 0 :(得分:1)

您的查询字符串应如下所示:

"INSERT INTO data_9_17 (partNumber, description, price) VALUES ('" + part[i] + "', '" + des[i] + "', '" + price[i] + "')";

您可以使用+来隐藏值。检查this

编辑:我犯了一个错误。没有把'放进去。现在修好了...... 无论如何,J Johnson是对的。由于SQL注入,最好使用Prepared Statements。

答案 1 :(得分:0)

您可以使用预准备语句,如下所示:

var query = 'INSERT INTO data_9_17 (partNumber, description, price) VALUES (?, ?, ?)';

con.query(query, [part[i], des[i], price[i]], function(err, results) ... )

// You will put your variables inside []

如果您想了解更多信息,请参阅mysql npm模块:

https://www.npmjs.com/package/mysql#escaping-query-values

答案 2 :(得分:0)

您需要将查询字符串与变量的值连接起来:

var sql = "INSERT INTO data_9_17 (partNumber, description, price) VALUES (" + part[i] + ", " + des[i] + ", " + price[i] + ")";

出于安全考虑,我建议您使用准备好的声明:

var sql = mysql.format("INSERT INTO data_9_17 (partNumber, description, price) VALUES (?, ?, ?)", [part[i], des[i], price[i]);

con.query(sql, function (err, result) {
.....
.....