Friday, July 3, 2020

Node.js + MySQL CRUD - GET,POST and DELETE

const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.json());

var mysqlConnection = mysql.createConnection({
host:'localhost',
user:'root',
database:'employeedb'
});

mysqlConnection.connect((err)=>{

if(!err)
console.log('DB Connection SuccessFull');
else
console.log('DB Connection Failed\n Error: '+JSON.stringify(err,undefined,2));
});


// Get All Employees
app.listen(3000, ()=>console.log('Express server is running at port No: 3000'));
app.get('/employees',(req,res)=>{
mysqlConnection.query('SELECT * FROM employees', (err, rows, fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});
// Get an Employees
app.get('/employees/:id',(req,res)=>{
mysqlConnection.query('SELECT * FROM employees WHERE id =?', [req.params.id],(err, rows, fields)=>{
if(!err)
res.send(rows);
else
console.log(err);
})
});

// Delete an Employees
app.delete('/employees/:id',(req,res)=>{
mysqlConnection.query('DELETE from employees WHERE id =?', [req.params.id],(err, rows, fields)=>{
if(!err)
res.send('Deleted SuccessFully');
else
console.log(err);
})
});

Tuesday, June 30, 2020

Creating Tables in MySQL from Node.js - MySQL / Node.js MySQL Create Database/ node js tutorial


Database

const express = require('express');
const mysql = require('mysql');

// create connection
const db = mysql.createConnection({
  host :'localhost',
  user :'root',
  password:'',
  });
  
  // connect 
  db.connect((err) => {
    if(err){
    throw err;
    }
    console.log('MySql Connected ....');
    
    });

const app = express();
// create DB 
app.get('/createDb', (req, res) => {
  let sql = 'CREATE DATABASE ujjwaldatabase';
  db.query(sql, (err, result) => {
      if(err) throw err;
      console.log(result);
      res.send('Database created...');
  });
});

app.listen('3000', () => 
{
  console.log('server started on port 3000');
});

Table


const express = require('express');
const mysql = require('mysql');

// create connection
const db = mysql.createConnection({
  host :'localhost',
  user :'root',
  password:'',
  database : 'ujjwaldatabase'

  });
  
  // connect 
  db.connect((err) => {
    if(err){
    throw err;
    }
    console.log('MySql Connected ....');
    
    });

const app = express();
// create DB 
app.get('/createpoststable', (req, res) => {
  let sql = 'CREATE TABLE profile(id int AUTO_INCREMENT, fullname VARCHAR(255), address VARCHAR(255), PRIMARY KEY(id))';
  db.query(sql, (err, result) => {
      if(err) throw err;
      console.log(result);
      res.send('Posts table created...');
  });
});

app.listen('3000', () => {
  console.log('Server started on port 3000');
});
Insert Data
// Insert post 1
app.get('/addpost1', (req, res) => {
  let post = {fullname:'Ujjwal Tripathi', address:'USA'};
  let sql = 'INSERT INTO profile SET ?';
  let query = db.query(sql, post, (err, result) => {
      if(err) throw err;
      console.log(result);
      res.send('Post 1 added...');
  });
});
// Insert post 2
app.get('/addpost2', (req, res) => {
  let post = {fullname:'Tripti Tripathi', address:'USA'};
  let sql = 'INSERT INTO profile SET ?';
  let query = db.query(sql, post, (err, result) => {
      if(err) throw err;
      console.log(result);
      res.send('Post 2 added...');
  });
});

Saturday, May 16, 2020

Angular 8/9 angular-datatables: DataTables using angular

Angular DataTables is one of the best datatable I have used in the angular. Angular DataTables is built on the top of JQuery DataTables.

Here is the complete working code and use this carefully:
1. Here are the basics commands, you need to run for latest angular 8/9 setup and environment:

$ npm install -g @angular/cli

$ ng new ang9datatables

$ cd ang9datatables

$ ng serve

//Here is the url, you need to run into your browser and see working angular test project
http://localhost:4200/
2. Here are the basics commands, you need to run into your terminal for datatable and its dependencies:

npm install jquery --save

npm install datatables.net --save

npm install datatables.net-dt --save

npm install angular-datatables --save

npm install @types/jquery --save-dev

npm install @types/datatables.net --save-dev

npm install ngx-bootstrap bootstrap --save

3. After done with commands add below code into you angular.json file:

...
"styles": [
              "src/styles.css",
              "node_modules/datatables.net-dt/css/jquery.dataTables.css",
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
            ],
            "scripts": [
            "node_modules/jquery/dist/jquery.js",
            "node_modules/datatables.net/js/jquery.dataTables.js",
            "node_modules/bootstrap/dist/js/bootstrap.js",
            ]
...

4. Now add below code into your app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {DataTablesModule} from 'angular-datatables';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    DataTablesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

5. Now add below code into app.component.ts file:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public data = [
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
    {name: 'ujjwal', email: 'ujjwaltechi1@gmail.com', website:'ujjwaltips.com'},
];

  title = 'angulardatatables';
  dtOptions: DataTables.Settings = {};
  ngOnInit() {
    this.dtOptions = {
      pagingType: 'full_numbers',
      pageLength: 5,
      processing: true
    };
}
}

6. Now add below code into app.component.html file:


<div class="container">
<table class="table table-striped table-bordered table-sm row-border hover" datatable [dtOptions]="dtOptions">
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
      <th>Website</th>
    </tr>
  </thead>
  <tbody>
   <tr *ngFor="let group of data">
         <td>{{group.name}}</td>
         <td>{{group.email}}</td>
         <td>{{group.website}}</td>
     </tr>
  </tbody>
</table>
<div>




Saturday, May 2, 2020

Example of Angular 9 Pagination Using ngx-pagination

app.component.html


<h1 style="text-align: center; color:orange; font-size:45px">Example of
Angular 9
Pagination Using ngx-pagination</h1>
<table class="table table-striped">
  <thead>
  <tr>
  <th>Gender</th>
  <th>Name</th>
  <th>Email</th>
  <th>Picture</th>
  </thead>
  <tbody>
    <tr *ngFor="let user of data | paginate: { id: 'listing_pagination',
    itemsPerPage: 10,
    currentPage: page,
    totalItems: totalRecords }">
  <td>{{user.gender}}</td>
<td>{{user.name.first}}</td>
<td>{{user.email}}</td>
<td><img src="{{user.picture.medium}}"></td>
 </tr>
  </tbody>
  </table>
  <div>
    <pagination-controls  id="listing_pagination" maxSize="5"
directionLinks="true"
(pageChange)="page = $event"></pagination-controls>
  </div>

app.component.ts

import { Component } from '@angular/core';
import { RandomService } from './random.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
data:Array<any>
totalRecords:number
page:number =1
  constructor(private random:RandomService)
  { this.data = new Array<any>() }
  ngOnInit() {
     this.getUsers();
    }
  getUsers(){
    this.random.getData().subscribe((data)=>{
    console.log(data)
    this.data = data.results
    this.totalRecords = data.results.length
    console.log(this.page)
    })

  }
}

app.module.ts
=> npm install ngx-pagination --save
=> import {NgxPaginationModule} from 'ngx-pagination'; 

=> imports: [NgxPaginationModule],


import {HttpClientModulefrom '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { RandomService } from './random.service';
import { NgxPaginationModule } from 'ngx-pagination';
@NgModule({
  declarations: [AppComponent],
  imports: [
    HttpClientModule,
    BrowserModule,
    NgxPaginationModule,
    AppRoutingModule,
  ],
  providers: [RandomService],
  bootstrap: [AppComponent]
})
export class AppModule { }

random.service.ts

=> ng g s random

import { Injectable } from '@angular/core';
import{HttpClientfrom '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RandomService {

  constructor(private http:HttpClient) { }
  getData():Observable<any>{
    const url ="https://randomuser.me/api?results=100"
    return this.http.get<any>(url)
  }
}


Fetching JSON data from REST APIs

data.json---------------------------------- [     {     "userId" : 1 ,     "id" : 1 ,     "title" : "sunt...