gpt4 book ai didi

javascript - Node.js MySQL : Select-statement depending on query string?

转载 作者:行者123 更新时间:2023-11-29 00:01:15 25 4
gpt4 key购买 nike

我正在 build 一个拍卖行。我正在使用 nodejs-mysql 包并且我有这个 nodejs server.js -主页代码,显示多个拍卖:

// loop
var pollingLoop = function() {
// Doing the database query
var query = connection.query('SELECT a.`id`,a.`product_id`,a.`price`,a.`random`,a.`price_end`,TIMESTAMPDIFF(SECOND,NOW(),a.`date_end`) AS duration,p.`price_retail` FROM `auctions` AS a LEFT JOIN `products` AS p ON p.`id` = a.`product_id` WHERE TIMESTAMPDIFF(SECOND,NOW(),a.`date_end`) > "-1" ORDER BY `duration` DESC,`id` DESC'),
auctions = [];
  1. $_GET['id'] 时,我怎样才能完成这个查询的更改?另一个可用SELECT -带有 WHERE 的语句-健康)状况?因为我想添加 WHERE auction='$_GET['id']'然后用于单个拍卖(但在服务器端)。
  2. 有没有办法让它更具可读性?因为当我按下 ENTERSELECT -语句根本不起作用。这是它在 nodejs-server-file server.js 上的样子: http://i.stack.imgur.com/37fDl.jpg

最佳答案

有两种方法可以将 Javascript 字符串分成多行:反斜杠和字符串连接。

用反斜杠分隔

var text = "Lorem ipsum dolor sit amet,\
consectetur adipisicing elit,\
sed do eiusmod tempor incididunt\
ut labore et dolore magna aliqua.";

用字符串连接分隔

var text = "Lorem ipsum dolor sit amet,"
+ "consectetur adipisicing elit,"
+ "sed do eiusmod tempor incididunt"
+ "ut labore et dolore magna aliqua.";

您需要动态地构建查询。像这样。

var query = 'SELECT \
a.`id`, \
a.`product_id`, \
a.`price`, \
a.`random`, \
a.`price_end`, \
TIMESTAMPDIFF(SECOND, \
NOW(), \
a.`date_end`) AS duration, \
p.`price_retail` \
FROM \
`auctions` AS a \
LEFT JOIN \
`products` AS p ON p.`id` = a.`product_id`';

var where = '';
if (condition) {
where = 'WHERE \
TIMESTAMPDIFF(SECOND, \
NOW(), \
a.`date_end`) > - 1';
} else {
where = "auction='$_GET['id']'";
}

var order = ' ORDER BY `duration` DESC , `id` DESC';
query = query + where + order
var res = connection.query(query), auctions = [];

附注这只是一个想法。例如,您可以使用 var where = array() 并用条件填充它。然后,只需遍历数组并通过 AND 创建查询连接条件。

更新:

如果不使用express模块,可以使用url模块获取GET参数。

var query = require('url').parse(req.url,true).query;

var id = query.id;
var some_par = query.some_par;

For url: /path/filename?id=123&some_par=456

然后您可以使用 id 变量构建查询。

关于javascript - Node.js MySQL : Select-statement depending on query string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29714175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com