Wednesday 17 May 2017

Printing out rows from a MySQL database in Node JS

first time poster so sorry if I break any nube rules!

I have to make a simple shop webpage that displays the contents of a MySQL database in a HTML table, and allows new products to be added to the database. I have got it working so the node app.js takes a header.html file and displays that at the top, and likewise displays a footer at the bottom using fs.ReadFileSync.

The main problem I'm having is printing out the MySQL database rows onto the webpage. I can see the rows are being printed on the console but on the webpage when the server is running it just prints [object Object] where the table should be.

Sorry if the code is a bit long and messy but any help at all would be greatly appreciated.

Thanks guys

var mysql = require('mysql');
var http = require('http');
var fs = require('fs');
var path = require('path');
var mime = require('mime');
var qs = require('querystring');
//var work = require('/header.html');
var shoppingCart = { // This for now contains a sample range of products to see if it works
  products: [
    {
      "id": 0,
      "Brand": "Tanglewood",
      "Model": "Singer",
      "Colour": "Natural",
      "Category": "Guitars",
      "Price": 600
    },
    {
      "id": 1,
      "Brand": "Epiphone",
      "Model": "Brasser",
      "Colour": "Sunburst",
      "Category": "Guitars",
      "Price": 800
    },
    {
      "id": 2,
      "Brand": "Chieftan",
      "Model": "Low D",
      "Colour": "Silver",
      "Category": "Irish",
      "Price": 230
    }

  ]
}; //this is the object that bought items will be stored in.

var footer = `

<div id = "footer">

<div id = "contactRight">
<p class = "contact">Email me: <a href="mailto:davidoregan140@gmail.com">
davidoregan140@gmail.com</a></p>
<p class = "contact">Call me: <a href="tel:+353214326100">021 2374599</a></p>
</div>

<div id = "addressLeft">
<address class = "address">
Visit us at:<br>
14a John's Street<br>
Kilkenny<br>
Ireland
</address>
</div>

</div>

`;


// SQL code here
var connection = mysql.createConnection({
  //connectionLimit: 10,
  host:'localhost',
  user:'root',
  password: '',
  database: 'inst_catalogue',
  port: 3306
});

connection.connect(function (err) {
  if (!err) {
    console.log('database is connected');
  } else {
    console.log("An error" + err.stack);
    console.log(err);
  }

});


var server = http.createServer(function(req, res) {


  var url = req.url;
  console.log("Request " + url + ' method ' + req.method);

  switch (req.method) {
    case 'POST':
    switch(req.url) {
      case '/':
      break;
      case '/addProduct':

//addProduct code
      var body = '';
      console.log("adding a new product");
      req.on('data', function(data) {
        body += data;
      });

    req.on('end', function () {
      var product = qs.parse(body);
      console.log(product);
      addProduct(product);
      showPage(req, res, showProducts());

    });

      break;

      case '/addToCart':
        //addToCart code here

      break;

    }
      break;
      case 'GET':
      switch(req.url) {
        case '/': //code to run if url is home page /
          showPage(req, res, showProducts());
          console.log("have to show stuff here");

console.log("connection closed");


        break;

        case '/showProducts':
        showPage(req, res, showProducts());
        break;
      }

      break;
    } // closes req.method
  }); // closes create server
  server.listen(3000);
  console.log("May 16 Server is listening on port 3000");





  // Below here we have all our functions that are declared and run separately

function showPage(req, res, str) {
  res.writeHead(200, {"content-type": 'text/html'}
);

  console.log("showpage function");
  var data = fs.readFileSync("./header_assversion.html", "utf-8");

  data += str;
  res.end(data);
}


  // function to add a new product to the database
  function addProduct(product) {
    connection.query("insert into products set ?", product,
    function(err, result) {
      if (err) {
        console.log(err);
        return;
      }
      console.log("the inserted product id was: ", result.insertId);
      console.log(product.brand);
    });

  } // closes addProduct


  // this function to show all products
  function showProducts() {
    console.log("Showing products");
var data = '<p>Where is my database?</p>';

    connection.query("select * from inst_catalogue.products ", function(err, rows, fields) {

      rows.forEach(function(result) {
        console.log(result.brand, result.model, result.colour, result.category, result.price, result.image_url);
      }) // closes for each


      data += '<table>';
      data += '<tr>';
      data += '<th>' + "Image" + '</th>';
      data += '<th>' + "Product ID" + '</th>';
      data += '<th>' + "Brand" + '</th>';
      data += '<th>' + "Model" + '</th>';
      data += '<th>' + "Colour" + '</th>';
      data += '<th>' + "Category" + '</th>';
      data += '<th>' + "Price in &euro;" + '</th></tr>';

      for(var i = 0; i < rows.length; i++){
        data += '<tr>';

        data += '<td><img style = "width: 100px" "height: 100px" src = ' + rows[i].image_url + '></td>';
        data += '<td style = "width: 80px">' + rows[i].id + '</td>';
        data += '<td style = "width: 80px">' + rows[i].brand + '</td>';
        data += '<td style = "width: 80px">' + rows[i].model + '</td>';
        data += '<td style = "width: 80px">' + rows[i].colour + '</td>';
        data += '<td style = "width: 80px">' + rows[i].category + '</td>';
        data += '<td style = "width: 80px">&euro;' + rows[i].price + '</td>';
        //data += '<td style = "width: 80px"><button onclick = "addToCart()">Add to cart</button><br><br>';


      //hopefully the button that takes the id of the instrument in the row and adds in to the cart
        data += '<td style = "width: 80px">';
        data += '<form action = "/shoppingCart/add" method = "POST">';
        data += '<input name = "id" type = "hidden" value = " ' + rows[i].id + ' "/>';
        data += '<input name = "brand" type = "hidden" value = " ' + rows[i].brand + ' "/>';
        data += '<input name = "model" type = "hidden" value = " ' + rows[i].model + ' "/>';
        data += '<input name = "colour" type = "hidden" value = " ' + rows[i].colour + ' "/>';
        data += '<input name= "category" type="hidden" value=" ' + rows[i].category + ' " />';
        data += '<button onclick = "addToCart()" class="add-button" type="submit">Add to le Cart!</button>';
        data += '</form>';

        data += '<button hidden id = "theForm" class = "spin">Delete from Store</button</td>';
      }

      data += "</table>";



    }); // closes connectionPool.query



    data += showCart();
    data += footer;
    return data;

  } // closes showProducts



via davidoregan140

No comments:

Post a Comment