Nodejs Course

- The Result Object
- Output data from Select result in HTML Table

Selecting From a MySQL Table

To select data from a table in MySQL database, use the "SELECT" statement.
- In this example we select all records with ID between 1 and 4 from the "friends"table, and display the return object:
const mysql = require('mysql');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'pass',
  database: 'nodedb',
  charset: 'utf8'
});

let sql ='SELECT * FROM friends WHERE id BETWEEN 1 AND 4';

pool.query(sql, (err, res, cols)=>{
  if(err) throw err;
  console.log(res);
});
Save the code above in a file called "mysql_select.js" and run the file:
node test/mysql_select.js
Will give you a result like this:
[
  { id: 1, name: 'Olpram', address: 'Heaven, Peace 0'},
  { id: 2, name: 'Xela', address: 'Good 71'},
  { id: 3, name: 'Rotciv', address: 'Helpful 4'},
  { id: 4, name: 'Noi', address: 'Loving st 652'}
]

The Result and Fields Objects

1. The result object is an array containing each row as an object.
To return e.g. the address of the second record, just refer to the second array object's address property (first row has index 0):
console.log(res[1].address);
Will give you a result like this:
Good 71

2. The third parameter of the callback function (here "cols") is an array with objects containing information about each field in the result.
If you add this code in the callback function of the query() method:
console.log(cols[0]);
- You'll get an object with informations about first field; like this:
{
  catalog: 'def',
  db: 'nodedb',
  table: 'friends',
  orgTable: 'friends',
  name: 'id',
  orgName: 'id',
  charsetNr: 33,
  length: 11,
  type: 3,
  flags: 16899,
  decimals: 0,
  default: undefined,
  zeroFill: false,
  protocol41: true
}
To get the field name, just refer to the "name" property:
var fname = fields[0].name;

Output data from Select result in HTML Table

Here is another Node.js code that selects data from MySQL, orders results by name, and output results in a html table.
const http = require('http');
const mysql = require('mysql');

const pool = mysql.createPool({
  host: '127.0.0.1',
  user: 'root',
  password: 'pass',
  database: 'nodedb',
  charset: 'utf8'
});

//html string that will be send to browser
var reo ='<html><head><title>Node.js MySQL Select</title></head><body><h1>Node.js MySQL Select</h1>{${table}}</body></html>';

//sets and returns html table with results from sql select
//Receives sql query and callback function to return the table
function setResHtml(sql, cb){
  pool.getConnection((err, con)=>{
    if(err) throw err;

    con.query(sql, (err, res, cols)=>{
      if(err) throw err;

      var table =''; //to store html table

      //create html table with data from res.
      for(var i=0; i<res.length; i++){
        table +='<tr><td>'+ (i+1) +'</td><td>'+ res[i].name +'</td><td>'+ res[i].address +'</td></tr>';
      }
      table ='<table border="1"><tr><th>Nr.</th><th>Name</th><th>Address</th></tr>'+ table +'</table>';

      con.release(); //Done with mysql connection

      return cb(table);
    });
  });
}

let sql ='SELECT name, address FROM friends WHERE id >1 ORDER BY name';

//create the server for browser access
const server = http.createServer((req, res)=>{
  setResHtml(sql, resql=>{
    reo = reo.replace('{${table}}', resql);
    res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
    res.write(reo, 'utf-8');
    res.end();
  });
});

server.listen(8080, ()=>{
  console.log('Server running at //localhost:8080/');
});
Save the code above in a file called "mysql_res_html.js" and run the file:
node test/mysql_res_html.js
Open the browser and access the address: //localhost:8080/
It will show a page like in this image:
HTML Table MySQL Select

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Select in MySQL, Output results in HTML Table

Last accessed pages

  1. Zodiac Signs JavaScript code (11023)
  2. AJAX and Forms (1938)
  3. A simple script ActionScript 3 (4329)
  4. Read Excel file data in PHP - PhpExcelReader (96689)
  5. Register and show online users and visitors (39376)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (250)
  2. Read Excel file data in PHP - PhpExcelReader (90)
  3. PHP Unzipper - Extract Zip, Rar Archives (75)
  4. The Four Agreements (73)
  5. The Mastery of Love (66)
Chat
Chat or leave a message for the other users
Full screenInchide