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 HTML element can be used to embed a SWF flash content?
<object> <div> <script>
<object type="application/x-shockwave-flash" data="file.swf" width="500" height="250">
 <param name="src" value="file.swf" />
 Your browser not support SWF.
</object>
Which CSS pseudo-class adds a style to an input form field that has keyboard input focus?
:active :focus :hover
input:focus {
  background-color: #88fe88;
}
Click on the instruction which converts a JSON string into a JavaScript object.
JSON.stringify(javascript_object) object.toString() JSON.parse(json_string)
var jsnstr = '{"url": "http://coursesweb.net/", "title": "Web Development Courses"}';
var obj = JSON.parse(jsnstr);
alert(obj.url);
Indicate the PHP function which can be used to create or write a file on server.
fopen() file_put_contents() file_get_contents()
if (file_put_contents("file.txt", "content")) echo "The file was created";
else echo "The file can not be created";
Select in MySQL, Output results in HTML Table

Last accessed pages

  1. JavaScript Course - Free lessons (31647)
  2. Volume and Surface Area Calculator for 3D objects (11276)
  3. Using v-model in form input fields (1051)
  4. jQuery UI draggable - Drag elements (11445)
  5. Display data from PHP Array, or MySQL in HTML table (26980)

Popular pages this month

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