简体   繁体   中英

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

I'm building an auction house. I'm using the nodejs-mysql package and I have this nodejs server.js -code for the main page, where multiple auctions are displayed :

// 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. How can I accomplish that this query is changed when a $_GET['id'] is available to another SELECT -statement with a WHERE -condition? Because I want to add WHERE auction='$_GET['id']' for a single auction then (but server-side).
  2. Is there a way to make it more readable? Because when I press ENTER the SELECT -statement won't work at all. This is how it looks on the nodejs-server-file server.js : http://i.stack.imgur.com/37fDl.jpg

There are two ways to break up a Javascript string into multiple lines: Backslashing and string concatenation.

Delimiting with backslashes

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

Delimiting with string concatenation

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

You need to build your query dinamically. Something like this.

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 = []; 

ps This is just an idea. For example, you can use var where = array() and fill it with conditions. Then, just loop over array and create query joining conditions by AND .

upd:

If you don't use express module, you can find GET parameters using url module.

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

Then you can build query with id variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM