Search code examples
mysqlnode.jsexpresspug

More than one control fields not working in node.js application


I have been creating a application using nodejs, express, jade and mysql. The problem is the front end has two select menu which needs to fetch data from two mysql tables. I am able to fetch only one. I am new to this, so please help me.

Output.jade file:-

    block sale
     select(id="cbosale", name="cbosale", class="custom-select custom-select-sm")
      option(value="") Select Sale
      each variable in data
       option(value=variable.SaleNo) #{variable.SaleNo}
    block state
     select(name="cbostate", id="cbostate", class="custom-select custom-select-sm")
      option(value="") Select State
      each state in data
       option(value=state.Statename) #{state.Statename}

App.js file:-

    app.get('/output', function(req, res){
     db.connect(function(err){
      db.query("SELECT DISTINCT(SaleNo) FROM tsales", function(err, result, fields){
       res.render('output', {title:"Output",data:result});
      })
      db.query("SELECT DISTINCT(Statename) FROM tstates", function(err, result, fields){
       res.render('output', {title:"Output",data:result});
      })
    })
   })

I know i am missing to identify which dropdown to render on which query, but i dont know how. Kindly help me.


Solution

    1. You can't render same page twice. res.render(... is used to compile(put values, generate view) and send it to server.

    2. You can use multiple queries in one statement. Check out this so answer on how to do so. You can then use both of these responses to render the page once together. The gist of that answer is

      var connection = mysql.createConnection({multipleStatements: true});

    Please note that, according to docs

    Support for multiple statements is disabled for security reasons (it allows for SQL injection attacks if values are not properly escaped).

    Make sure you sanitise inputs on server side before any query. Once enabled, you can execute queries with multiple statements by separating each statement with a semi-colon ;. Result will be an array for each statement.