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 atribut specifica metoda HTTP de trimitere (GET, POST) a datelor din formular?
action method value
<form action="script.php" method="post"> ... </form>
Ce proprietate CSS adauga umbra la chenar?
background-image box-shadow border-radius
#id {
  background-color: #bbfeda;
  box-shadow: 11px 11px 5px #7878da;
}
Clic pe functia care elimina primul element dintr-un array?
pop() push() shift()
var fruits = ["mar", "cireasa", "banana"];
fruits.shift();
alert(fruits.length);           // 2
Indicati functia cu care se poate verifica daca un anumit modul e instalat in PHP.
function() filetype() extension_loaded()
if(extension_loaded("PDO") === true) echo "PDO este valabil."
Alegeti verbul auxiliar corect care trebuie in propozitia: " ... I listen to music?".
has have Can
 Can I listen to music?
- Pot asculta muzica?
Alegeti verbul corect care trebuie in propozitia: "Me ... las frutas dulces"
están gustan gusta
Me gustan las frutas dulces.
- Imi plac fructele dulci.
Select in MySQL, Creare tabel HTML cu date din Select

Last accessed pages

  1. Pacea Inseptita (452)
  2. Pronumele in limba engleza - Pronouns (55070)
  3. Scriere scripturi PHP elementare (6461)
  4. Curs PHP MySQL, Tutoriale si Scripturi PHP (129169)
  5. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (279268)

Popular pages this month

  1. Cursuri si Tutoriale: Engleza, Spaniola, HTML, CSS, Php-Mysql, JavaScript, Ajax (61)
  2. Gramatica limbii spaniole. Indrumator si prezentare generala (52)
  3. Limba spaniola curs online incepatori si avansati (26)
  4. Accentul si Pronuntia (24)
  5. Teste spaniola - Tests y ejercicios de Español - Gramática (23)