Asked 7 years ago
17 Aug 2017
Views 1648
yogi

yogi posted

how to run two Mysql Query in one function with node js in Express Framework

i am dealing with a form for edit where i need to get data from table for parameter id

exports.edit= function(req,res){
  var id = req.params.id;
  var query = connection.query('SELECT * FROM data WHERE id = ?',[id],function(err,data)
  {
           res.render('admin/edit',{page_title:"Edit",raws:data});
         });
};


but form have drop down which also come from database so i want to use two query one for data edit fetch and second for the drop down list

  <form id="edit" method="post" action="/admin/edit/<%=data[0].id%>">
<select class="form-control" type="text" placeholder="" name="data1" required>
		                    		<option>Select Category</option>

</select>
</form>


so i can run two query in same function so i get the drop down value from database table and form value also from database table

===
what i tried

exports.edit= function(req,res){
  var id = req.params.id;
  var query = connection.query('SELECT * FROM dropdownoptionlist  ',[id],function(err,data)
  {
           res.render('admin/edit',{page_title:"Edit",raws:data});
         });
  var query = connection.query('SELECT * FROM data WHERE id = ?',[id],function(err,data)
  {
           res.render('admin/edit',{page_title:"Edit",raws:data});
         });
};

but in this case it goes to fetch only dropdownoptionlist only not from data
so how can i run two query and pass that parameter to template and render it properly

Cimb

Cimb
answered Apr 24 '23 00:00

To execute two MySQL queries within a single function using Node.js and Express framework, you can use the mysql package to connect to your database and perform the necessary queries. Here's an example implementation:



const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'username',
  password: 'password',
  database: 'mydatabase'
});

function executeTwoQueries(callback) {
  connection.connect(function(err) {
    if (err) {
      console.error('Failed to connect to MySQL:', err);
      callback(err, null);
    } else {
      console.log('Connected to MySQL.');

      // Execute the first query
      connection.query('SELECT * FROM users', function(err, results1) {
        if (err) {
          console.error('Error executing the first query:', err);
          callback(err, null);
        } else {
          console.log('First query executed successfully.');

          // Execute the second query
          connection.query('SELECT * FROM products', function(err, results2) {
            if (err) {
              console.error('Error executing the second query:', err);
              callback(err, null);
            } else {
              console.log('Second query executed successfully.');

              // Close the database connection
              connection.end();

              // Return the results to the callback
              callback(null, { results1: results1, results2: results2 });
            }
          });
        }
      });
    }
  });
}

The executeTwoQueries function takes a callback function as an argument, which will be called once the queries are completed. It first creates a connection to the MySQL database using the mysql.createConnection function.

Then, it executes the first query (SELECT * FROM users ) using the connection.query function and passes a callback function to handle the results. If there's an error, the function logs an error message and calls the callback with the error. If the query is successful, it logs a success message and executes the second query (SELECT * FROM products) in a similar way.

Once both queries have completed successfully, the function closes the database connection using the connection.end() function and passes the results back to the callback using an object with two properties: results1 and results2 .

You can call the executeTwoQueries function from your Express route or controller, passing a callback function to handle the results. For example:



app.get('/two-queries', function(req, res) {
  executeTwoQueries(function(err, results) {
    if (err) {
      res.status(500).send('Failed to execute queries.');
    } else {
      res.send(results);
    }
  });
});

In this example, the app.get function creates a new route that will call the executeTwoQueries function when the user visits the URL /two-queries. The callback function handles any errors and sends the results back to the client using the res.send function
Post Answer