Curs Javascript

- Obiecte cu Randuri si Coloane
- Creare tabel HTML cu date din Select

Select in tabel MySQL

Pentru a face select intr-un tabel din baza de date MySQL, se foloseste instructiunea "SELECT".
- In acest exemplu vom selecta randurile cu ID-ul intre 1 si 4 din tabelul "friends" si vom afisa obiectul returnat:
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);
});
Salveaza codul de mai sus intr-un fisier "mysql_select.js si ruleaza fisierul:
node test/mysql_select.js
Vei obtine un rezultat ca acesta:
[
  { 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'}
]

Obiecte cu Randuri si Coloane

1. Obiectul result este un array cu fiecare rand ca un obiect.
Pentru a returna de ex. valoarea din coloana "address" din al doilea rand, faceti referire la proprietatea "address" al obiectului din al doilea array (primul rand are index 0).
console.log(res[1].address);
Iti va da un rezultat ca acesta:
Good 71

2. Al treilea parametru a functiei callback (aici "cols") este un array cu obiecte ce contin informatii despre fiecare coloana din rezultat.
Daca adaugi acest cod in functia callback a metodei query():
console.log(cols[0]);
- Vei obtine un obiect cu informatii despre prima coloana:
{
  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
}
Pentru a obtine numele coloanei, folositi proprietatea "name":
var fname = fields[0].name;

Creare tabel HTML cu date din Select

Aici aveti un cod Node.js care selecteaza date din MySQL, ordoneaza rezultatul dupa nume si afiseaza rezultatul intr-un tabel html.
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/');
});
Salveaza codul de mai sus intr-un fisier numit "mysql_res_html.js" si ruleaza fisierul:
node test/mysql_res_html.js
Deschide browserul si acceseaza adresa: //localhost:8080/
Va afisa o pagina ca in aceasta imagine:
HTML Table MySQL Select

Un Test simplu in fiecare zi

HTML
CSS
JavaScript
PHP-MySQL
Engleza
Spaniola
Care tag este element de tip bloc?
<div> <img> <span>
<div>Web Programming and Development</div>
Care cod CSS afiseaza textul subliniat?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Clic pe functia JavaScript care apeleaza o alta functie dupa un anumit timp.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Clic pe instructiunea care returneaza numarul total de elemente dintr-un array asociativ.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "mar"), "veggie" =>["ceapa", "rosie"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
Indicati Viitorul Perfect la negativ al verbului din paranteze, in propozitia: "The child (to not play) by Sunday".
has't played haven't been playing will haven't played
The child will haven't played by Sunday.
- Copilul nu s-ar fi jucat pana duminica.
Indicati Viitorul Perfect pentru verbul "contar" (a povesti) la forma "Él".
habrá contado va a contar contaba
Él no habrá contado el cuento.
- El nu ar fi spus povestea.
Select in MySQL, Creare tabel HTML cu date din Select

Last accessed pages

  1. Download carti electronice si programe pentru Limba Engleza (44881)
  2. Proverbe, expresii si zicatori (25200)
  3. Creare si editare pagini HTML (87132)
  4. Prezentul simplu si continuu - Present Tense Simple and Continuous (149870)
  5. Prezent perfect si Prezent perfect continuu - Present perfect and Continuous (91648)

Popular pages this month

  1. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (358)
  2. Gramatica limbii spaniole. Indrumator si prezentare generala (277)
  3. Gramatica limbii engleze - Prezentare Generala (137)
  4. Teste spaniola - Tests y ejercicios de Español - Gramática (134)
  5. Limba spaniola curs online incepatori si avansati (131)