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 is a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Select in MySQL, Output results in HTML Table

Last accessed pages

  1. Date and Time in ActionScript 3 (10091)
  2. jQuery parent, children and nth-child() (13873)
  3. RegExp - Regular Expressions in ActionScript (4713)
  4. JavaScript strip_tags and stripslashes (8829)
  5. Complex Shapes with a single DIV and CSS (3711)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (643)
  2. The Mastery of Love (75)
  3. CSS cursor property - Custom Cursors (71)
  4. Read Excel file data in PHP - PhpExcelReader (67)
  5. PHP-MySQL free course, online tutorials PHP MySQL code (48)