Tuesday, 17 April 2018

How to implement Real time notification in NodeJs

Here are simple steps to create real time notification using NodeJs, Socket.io and Mysql

Socket.IO enables real-time bidirectional event-based communication.It has two parts: a client-side library that runs in the browser, and a server-side library for node.js. Install Socket.IO


npm install --save socket.io

I hope you have install express and mysql. This are basic few code inside server file.

var express = require( 'express' );
var app = express();
app.use( express.static( __dirname + '/public') );

var mysql = require('mysql');
var server = require( 'http' ).Server( app );
var io = require( 'socket.io' )( server );
server.listen( 3000, function(){
  console.log( 'listening on *:3000' );

} );
app.get('/', function(req, res) {
   res.sendFile(__dirname + '/index.html');

});

The require('socket.io')(http) creates a new socket.io instance attached to the http server.

Now make mysql connection

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "nodejs"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

});

Now in index.html I add the following snippet before the </body>:
It load the socket.io-client, and then connect with server.
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();

</script>

Now in server file I add the following snippet. It will check connection event for incoming sockets,

io.on('connection', function(socket){
  console.log('a user connected');
});

Now add event on client side
socket.on('user list', function(list){
$('.blink_me').text(list[0].totalUsers);

});

Handle event in server side.

io.on('connection', function(socket){
  setInterval(function() { // send total users after 4 second
      con.query("SELECT count(*) as totalUsers FROM customer", function(err, result) {
if(err){
throw err;
}
io.emit('user list', result);
  });
   }, 4000);

});

Some Important points

Socket Event Handling

In order to send an event to everyone, Socket.IO gives us the io.emit:

io.emit('some event', { for: 'everyone' });

You can create and execute custom events using the socket.emit function.

eg: socket.emit('customEvent', { content: 'A custom event created !'});

in view file use it
var socket = io();
socket.on('customEvent', function(data){document.write(data.content)});

You can also emit events from the client side. To emit an event from your client, use the emit function on the socket object.
var socket = io();
socket.emit('clientEvent', 'Sent an event from the client!');

inside server file
socket.on('clientEvent', function(data) {
  console.log(data);

});

Socket Broadcasting
Broadcasting means sending a message to all connected clients.To broadcast an event to all the clients, we can use the io.sockets.emit method.

inside server file:
var clients = 0;
io.on('connection', function(socket) {
   clients++;
   io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});
   socket.on('disconnect', function () {
      clients--;
      io.sockets.emit('broadcast',{ description: clients + ' clients connected!'});
   });
});

On the client side
socket.on('broadcast',function(data) {
document.write(data.description);

});

Thursday, 28 December 2017

How to Implement CRUD in Node js With MySQL

How to Implement CRUD in Node.js With MySQL

In this post, we are going to create a simple CRUD application in Node.js with MySQL as the database. We are using EJS as the template engine.

Before get started with this tutorial: You need to have Node installed. Read my previous post for Node.js installation.






Step 1: Create index.js as main file and package.json file

package.json
{
"name": "curdnode",
"version": "1.0.0",
"description": "Create simple curd example in nodejs",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "sangi",
"license": "ISC"
}

index.js
console.log('Welcome You');

Now open up your command line and run :
npm start

Output:
Welcome You

Stop the current server by hitting CTRL + C in the command line.

Step 2: Now install required dependency for CRUD application

a) Express dependency
   npm install express --save
 
b) Path dependency
   npm install path --save
 
c) Body Parser dependency
   npm install body-parser --save
 
d) MySQL dependency
   npm install mysql --save
 
e) EJS template
   npm install ejs --save
 
Step 3: We are using http method to handling GET/POST request
    var http = require("http");

Now use all dependency

var express = require('express');
var path = require('path');
var app = express();
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "",
  database: "nodejs"
});
con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

Step 4: Now create port and run from browser
   app.listen(3015, function () {
  console.log('Example app listening on port 3015!');
   });
 
   Now Run in browser localhost:3015
 
 
CRUD - Implementation begain from here

Note: For view handling create folder views at root directory

Use GET method for GET type request handling
app.get('/', function (req, res) {
    res.render('pages/index', {
title : 'Node Curd'
    });
});

Inside views folder create pages folder. Inside pages folder create index.ejs file

views/pages/index.ejs

We are using EJS template engine

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- include elements head -->
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <!-- include elements head -->
    <% include ../partials/header %>
</header>

<main>
    <div class="jumbotron">
        <h1>This is great</h1>
        <p>Welcome to templating using EJS</p>
<p><%= tagline %></p>
<ul>
    <% drinks.forEach(function(drink) { %>
        <li><%= drink.name %> - <%= drink.drunkness %></li>
    <% }); %>
</ul>
    </div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>


views/partials/head.ejs
Partial view include in index file
<meta charset="UTF-8">
<title><%= title %></title>

<!-- CSS (load bootstrap from a CDN) -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
    body    { padding-top:50px; }

</style>

views/partials/header.ejs
Partial view include in index file

<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">
<span class="glyphicon glyphicon glyphicon-tree-deciduous"></span>
EJS Is Fun
</a>
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/customer">Customer</a></li>
<li><a href="/add-customer">Add New Customer</a></li>
</ul>
</div>
</div>

</nav>

views/partials/header.ejs
Partial view include in index file
<p class="text-center text-muted">© Copyright 2017 Appt Medical</p>

Node Create add method inside index.js file
app.get('/add-customer', function(req, res) {
    res.render('pages/add-customer',{title : 'Add New Customer'});
});

Create its views 
views/pages/add-customer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<% include ../partials/head %>
</head>
<body class="container">

<header>
<% include ../partials/header %>
</header>

<main>
<div class="row">
<div class="col-sm-8">    
<div class="well">
   <form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-sm-2" for="inputName">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="name">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" name="email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputPassword">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" name="password">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputAddress">Address</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="inputAddress" placeholder="Address" name="address"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputPhone">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" name="phone">
</div>
</div>
<div class="form-group">        
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
</div>
</div>

<div class="col-sm-4">        
<div class="well">
<h3>Look I'm A Sidebar!</h3>
</div>
</div>

</div>
</main>

<footer>
<% include ../partials/footer %>
</footer>

</body>
</html>

Create POST method handle request and insert into database
app.post('/add-customer', function(request, response){
response.setHeader('Content-Type', 'application/json');
var users={
"name":request.body.name,
"email":request.body.email,
"password":request.body.password,
"address":request.body.address,
"phone":request.body.phone,
}

con.query('INSERT INTO customer SET ?',users, function (error, results, fields) {
if (error) {
console.log("error ocurred",error);
response.send({
  "code":400,
  "failed":"error ocurred"
})
}else{
console.log('The solution is: ', results);
return response.redirect('/customer');
}
});

});

Node Create edit method inside index.js file
app.get('/customer/:id',function(req,res) {
var customerId = req.params.id;
con.query('select * from customer where id = ?', customerId, function(err,result) {
res.render('pages/edit-customer',{title : 'Customer',customer:result});
});
});

Create its views 
views/pages/edit-customer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
<div class="row">
    <div class="col-sm-8">    
        <div class="well">
           <form class="form-horizontal" method="POST">
<div class="form-group">
<label class="control-label col-sm-2" for="inputName">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputName" placeholder="Name" name="name" value="<%=  customer[0].name %>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputEmail">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="inputEmail" placeholder="Email" name="email" value="<%=  customer[0].email %>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputAddress">Address</label>
<div class="col-sm-10">
<textarea class="form-control" rows="5" id="inputAddress" placeholder="Address" name="address"><%=  customer[0].address %></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="inputPhone">Phone</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputPhone" placeholder="Phone" name="phone" value="<%=  customer[0].phone %>">
</div>
</div>
<div class="form-group">        
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
        </div>
    </div>

    <div class="col-sm-4">        
        <div class="well">
            <h3>Look I'm A Sidebar!</h3>
        </div>
    </div>

</div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>
</html>

Create POST method handle request and update into database
app.post('/customer/:id',function(req,res) {
var customerId = req.params.id;
res.setHeader('Content-Type', 'application/json');
var users={
"name":req.body.name,
"email":req.body.email,
"address":req.body.address,
"phone":req.body.phone,
}
console.log(users);
con.query(' UPDATE customer SET ? where id = ? ',[users,customerId], function (error, results, fields) {
if (error) {
console.log("error ocurred",error);
res.send({
  "code":400,
  "failed":"error ocurred"
})
}else{
console.log('The solution is: ', results);
return res.redirect('/customer');
}
});

});

Create method list all rows index.js file
app.get('/customer', function(req, res) {
con.query("SELECT * FROM customer", function(err, result) {
if(err){
            throw err;
}
req.flash('success', 'Registration successfully');
res.locals.message = req.flash();
res.render('pages/customer',{title : 'Customer',customer:result});
  });
});

Create its views 
views/pages/customer.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <% include ../partials/head %>
</head>
<body class="container">

<header>
    <% include ../partials/header %>
</header>

<main>
<div class="row">
    <div class="col-sm-8">  
<% if(locals.message){ %>
    <div class="alert alert-success" role="alert">
        <strong>Well done!</strong> <%=message.success%>
    </div>
<% } %>
        <div class="well">
            <h3>Teacher Listing</h3>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<% for(i=0;i<customer.length;i++){ %>
<tr>  
<td><%=  customer[i].name %>&nbsp;</td>  
<td><%=  customer[i].email %>&nbsp;</td>
<td><%=  customer[i].address %>&nbsp;</td>
<td><%=  customer[i].phone %>&nbsp;</td>
<td><a href="/customer/<%=  customer[i].id %>">Edit</a>
<a href="/delete/<%=  customer[i].id %>">Delete</a>
</td>
</tr>                                   
<% } %>
</tbody>
</table>
        </div>
    </div>
</div>
</main>

<footer>
    <% include ../partials/footer %>
</footer>

</body>

</html>

Create delete method inside index.js file
app.get('/delete/:id',function(req,res) {
var customerId = req.params.id;
con.query('DELETE FROM customer WHERE id = ?', customerId, function (err, result) {
if (err) throw err;
console.log('Deleted ' + result.affectedRows + ' rows');
}
);
return res.redirect('/customer');

});

Friday, 8 September 2017

How to Create a jQuery Autocomplete in Wordpress

How to Create a jquery-ui Autocomplete in wordpress.

Autocomplete provides suggestions while you type into the text field. In Wordpress we fetch dynamically matched pattern.

Include javascript and css files in header.

Create action inside functions.php or inside plugin code.

add_action('wp_head', 'custom_register_scripts');

function custom_register_scripts(){
wp_register_style( 'sangi_jquery_ui_css', plugin_dir_url(__FILE__) . 'css/jquery-ui.css', false,'1.0.0' );
wp_enqueue_style( 'sangi_jquery_ui_css' );

wp_register_script('sangi_jquery_ui_js',plugin_dir_url(__FILE__) . 'js/jquery-ui.js',array('jquery'),'1.1', false);
wp_enqueue_script('sangi_jquery_ui_js');

wp_localize_script( 'sangi_autocomplete', 'jqueryAutocomplete', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'sangi_autocomplete' );
}

Now add script for Autocomplete

jQuery("#destination_id").autocomplete({
source: function(req, response){
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: jqueryAutocomplete.ajaxurl,
data: 'action=wpyog_search_program&term='+req.term,
success: function(data) {
response(jQuery.map(data, function (item) {
return {
label: item.name,
value: item.id
};
}));
}
});
},
select: function(event, ui) {
jQuery("#destination_id").val(ui.item.label); 
jQuery("#program_id").val(ui.item.value); 
return false;
// save selected id to hidden input
},
minLength: 3
});

Create action inside functions.php or inside your plugin code.

add_action('wp_ajax_nopriv_wpyog_search_program', 'wpyog_search_program');
add_action('wp_ajax_get_wpyog_search_program', 'wpyog_search_program');
function wpyog_search_program(){
global $wpdb;
$suggestions=array();
$search_key = $_REQUEST['term'];
$table_trips = $wpdb->prefix . "wpyog_trips"; // Use custom table for data fetch
    $tripRows = $wpdb->get_results("SELECT id, title, description from $table_trips where title like '%$search_key%' or description like '%$search_key%'");
foreach($tripRows as $row){
$suggestion = array();
        $suggestion['id'] = $row->id;
        $suggestion['name'] = (!empty($row->title))?$row->title:$row->description;
$suggestions[]= $suggestion;
}  
    echo json_encode($suggestions);
    // Don't forget to exit!
    exit;
}

Monday, 28 August 2017

Simple CRUD Example in Cakephp

Simple CRUD Operation in CakePHP 2.x

This tutorial will explain about CRUD Operation in CakePHP. Here we will perform mysql Insert, Select, Update, Delete operation in cakePHP Framework. As we know CakePHP uses MVC design patterns.

Here we will cover following points:
1. MySQL Database Table Used
2. We are using CakePHP Version 2.x
3. Create/Select/Update/Delete records.

We have assume that you have already created you database table. Here is simple users table structure.
CREATE TABLE `users` (
  `id` bigint(20) UNSIGNED NOT NULL primary key AUTO_INCREMENT,
  `firstname` varchar(128) NOT NULL,
  `lastname` varchar(128) DEFAULT NULL,
  `username` varchar(128) DEFAULT NULL,
  `password` varchar(128) DEFAULT NULL,
  `email` varchar(128) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
)

Create action inside Users controller.
Controller: app/Controller/UsersController.php

Create add function inside controller: add() function is used to save data. Here we are using "User" model.
public function add() 
{
  if ($this->request->is(array('post', 'put'))) {
{
$this->User->create();
if ($this->User->save($this->request->data)) 
{
$this->Session->setFlash(('Users has been saved successfully'));
return $this->redirect(array('controller' => 'Users', 'action' => 'index'));
} else 
{
$this->Session->setFlash(('User could not be saved. Please, try again.'));
}
}
}

Create view file for add action
View: app/View/Users/add.ctp

<h1>Add User</h1>
<?php
echo $this->Form->create('User');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('username');
echo $this->Form->input('password');
echo $this->Form->input('email');
echo $this->Form->end('Save');
?>

Create edit function: In edit(), here $id parameter to access an existing record. 
public function edit($id = null) {
if (!$this->User->exists($id)) {
throw new NotFoundException(_('Invalid user'));
}
if ($this->request->is(array('post', 'put'))) {
$this->User->id = $id;
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->User->findById($id);
}
}

View file for edit action
View: app/View/Users/edit.ctp

<h1>Edit User</h1>
<?php
echo $this->Form->create('User');
echo $this->Form->input('firstname');
echo $this->Form->input('lastname');
echo $this->Form->input('username');
echo $this->Form->input('email');
echo $this->Form->input('id', array('type' => 'hidden'));
echo $this->Form->end('Save User');
?>

Create Delete Function: delete() function deletes the data which is ID. 
public function delete($id = null) {
$this->User->id = $id;
if (!$this->User->exists()) {
throw new NotFoundException(('Invalid user'));
}
if ($this->User->delete()) {
$this->Session->setFlash(('The user has been deleted.'));
} else {
$this->Session->setFlash(('The user could not be deleted. Please, try again.'));
}
return $this->redirect(array('action' => 'index'));
}

Index Function: index() action is used to fetch data from database users table 

public function index()
{
$users = $this->User->find('all');
$this->set('users', $users);
}
View: app/View/Users/index.ctp
<h2>Users</h2>
<!-- link to add new users-->
<div class='pull-right'>
    <?php echo $this->Html->link( '+ New User', array( 'action' => 'add' ) ); ?>
</div> 
<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Username</th>
        <th>Email</th>
        <th>Actions</th>
    </tr>
<?php
    //loop to show all fetched records
    foreach( $users as $user ){
     
        echo "<tr>";
            echo "<td>{$user['User']['firstname']}</td>";
            echo "<td>{$user['User']['lastname']}</td>";
            echo "<td>{$user['User']['username']}</td>";
            echo "<td>{$user['User']['email']}</td>";            
            //here are the links to edit and delete actions
            echo "<td class='actions'>";
                echo $this->Html->link( 'Edit', array('action' => 'edit', $user['User']['id']) );
                echo $this->Form->postLink( 'Delete', array(
                        'action' => 'delete', 
                        $user['User']['id']), array(
                            'confirm'=>'Are you sure you want to delete that user?' ) );
            echo "</td>";
        echo "</tr>";
    }
?>    
</table>

Tuesday, 8 August 2017

How to use Ajax in WORDPRESS

How AJAX Works In WordPress

What's AJAX?
AJAX stands for Asynchronous JavaScript And XML. It is the use of the XMLHttpRequest object to communicate with servers, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.

Step1: Define the Ajax URL.
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' );?>';

Step2: Define its action and perform with using POST method

var emailAddress = jQuery('#uemail').val();
var searchData = {
action: 'get_registered_email',
email_address:emailAddress,
}

Step 3: Perform ajax request
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: searchData,
success: function(data){
  jQuery("div#divLoading").removeClass('show');
  jQuery('#memberResult').html(data);
  //alert(data);
},
error: function(errorThrown){
alert(errorThrown);
}
});

Step 4: Use Wordpress 2 ajax hooks i.e wp_ajax_your_action and wp_ajax_nopriv_your_action

Example: In Our ajax request we have defined action name as "get_registered_email" so our ajax action hook will be as follows:

add_action('wp_ajax_nopriv_get_registered_email', 'wpyog_get_registered_email'); // for not logged in users
add_action('wp_ajax_get_registered_email', 'wpyog_get_registered_email');

Step5: Ajax request callback function
function wpyog_get_registered_email(){
wp_die();
}

Full Example 1:
JavaScript: 
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' );?>';
var emailAddress = jQuery('#uemail').val();
var searchData = {
action: 'get_registered_email',
email_address:emailAddress,
}
jQuery.ajax({
url: ajaxurl,
type: "POST",
data: searchData,
success: function(data){
  jQuery("div#divLoading").removeClass('show');
  jQuery('#memberResult').html(data);
  //alert(data);
},
error: function(errorThrown){
alert(errorThrown);

});

functions.php
add_action('wp_ajax_nopriv_get_registered_email', 'wpyog_get_registered_email'); // for not logged in users
add_action('wp_ajax_get_registered_email', 'wpyog_get_registered_email');
function wpyog_get_registered_email(){
echo "<pre>"; print_r($_REQUEST); exit;
wp_die();
}


Full Example 2:

// create nonce using php
//$nonce = wp_create_nonce("sangi_profile_update");
add_action( 'init', 'sangi_script_enqueuer' );

function sangi_script_enqueuer() {
   wp_register_script( "sangi_script", WP_PLUGIN_URL.'/my_plugin/sangi_script.js',array('jquery') );
   wp_localize_script( 'sangi_script','myAjax',array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));        
   wp_enqueue_script( 'jquery' );
   wp_enqueue_script( 'sangi_script' );

}

sangi_script.js
jQuery(document).ready( function() {

   jQuery(".user_action").click( function(e) {
      e.preventDefault(); 
      post_id = 12;
      nonce = 'sangi_profile_update';

      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {action: "save_sangi_profile", post_id : post_id, nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
               console.log(response.view_count)
            }
            else {
               alert("Your vote could not be added")
            }
         }
      })   

   })

})

add_action("wp_ajax_save_sangi_profile", "save_sangi_profile");
add_action("wp_ajax_nopriv_save_sangi_profile", "save_sangi_profile");

function save_sangi_profile() {

   if ( !wp_verify_nonce( $_REQUEST['nonce'], "sangi_profile_update")) {
      exit("No naughty business please");
   }   

   $result['type'] = "success";
   $result['view_count'] = 11;

   if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
      $result = json_encode($result);
      echo $result;
   }
   else {
      header("Location: ".$_SERVER["HTTP_REFERER"]);
   }

   die();


}

Monday, 10 July 2017

How to create STAR PATTERN in PHP

STAR Pattern Printing using PHP for loop


Pattern:
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *

Code:
for($i=0; $i<5; $i++)
{
for($j=0; $j<5; $j++)
{
print_r(" * ");
}
print_r("<br/>");
}



Pattern:
*
* *
* * *
* * * *
* * * * *

Code:
for($i=0; $i<5; $i++)
{
for($j=0; $j<=$i; $j++)
{
print_r(" * ");
}
print_r("<br/>");
}

Pattern:
             *
         * *
       * * *
    * * * *
 * * * * *

Code:
for($i=0; $i<5; $i++)
{
for($j=5; $j>=$i; $j--)
{
print_r("&nbsp; "); 
}
for($k=0; $k<=$i; $k++)
{
print_r("*");
}
print_r("<br/>");
}

Pattern:
* * * * *
   * * * *
      * * *
         * *
            *

Code:
$temp = 1;
for($i=5; $i>=1; $i--)
{
for($k=$temp; $k>=0; $k--)
{
print_r(" &nbsp;");
}
for($j=$i; $j>=1; $j--)
{
print_r("*");
}
$temp = $temp + 1;
print_r("<br/>");
}



Pattern:
* * * * *
* * * *  
* * *    
* *      
*

Code:
for($i=1; $i<=5; $i++)
{
for($j=5; $j>=$i; $j--)
{
print_r("*");
}
for($k=1; $k<=$i; $k++)
{
print_r("&nbsp; ");
}
print_r("<br/>");
}

Pattern:
AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC BBA BBB
BBC BCA BCB BCC CAA CAB CAC CBA CBB CBC CCA CCB CCC 

Code:
for($ch1='A' ; $ch1<='C' ; ++$ch1)
{
for($ch2='A' ; $ch2<='C' ; ++$ch2)
{
for($ch3='A' ; $ch3<='C' ; ++$ch3)
{
echo sprintf(" %s%s%s", $ch1, $ch2, $ch3);
}

}
}

Pattern:
A B C D E F G G F E D C B A
    A B C D E F F E D C B A
      A B C D E E D C B A
          A B C D D C B A
              A B C C B A
                 A B B A
                     A A 

Code:
for($i=7; $i>=1; $i--)
{
for($spc=6; $spc>=$i; $spc--)
{
print_r("&nbsp; ");
}

$asci=65;
for($j=1; $j<=$i; $j++)
{
echo sprintf("%c",$asci++);
}
for($j=$i-1; $j>=0; $j--)
{
echo sprintf("%c",--$asci);
}
print_r("<br/>");
}

Tuesday, 13 June 2017

6 guaranteed steps how to create CRON JOB FUNTION in wordpress

Create Cron Job function in Wordpress plugin
Step 1: Register function on plugin activate 
register_activation_hook(__FILE__, 'activate_one');

Step 2: add_filter function for interval
//Filter for Adding multiple intervals
add_filter( 'cron_schedules', 'intervals_schedule' );


// define interval function
 function intervals_schedule($schedules) {
  $schedules['everyminute'] = array(
   'interval' => 60, // Every 1 minutes
   'display'  => __( 'Every 1 minutes' )
  );
  return $schedules;
 }

Step 3: Activate hook function
 //Schedule a first action if it's not already scheduled
 function activate_one() {
  if (!wp_next_scheduled('wpyog_cron_action')) {
   wp_schedule_event( time(), 'everyminute', 'wpyog_cron_action');
  }
 }

Step 4: Cron hook function

  //Hook into that action that'll fire after 1 minutes
  add_action('wpyog_cron_action', 'execute_one');

 function execute_one()
 {
  global $wpdb; 
  $to = "psudhir20@gmail.com";
  $subject = "Wordpress Cron Test";
  $body = "This cron is runing after each 30 minutes \n\n";
  $body .= "Player Name = Sudhir\n";
  $body .= "Injury Status = Fit\n";
  $body .= "Description = Available\n";
  $headers = array(
   'Reply-To' => " Sudhir <er.sudhir2487@gmail.com>"
  );
  wp_mail($to, $subject, $body,$headers); 
 }
Step 5: Stop cron after deactivation
 register_deactivation_hook(__FILE__, 'my_deactivation');

 function my_deactivation() {
  wp_clear_scheduled_hook('wpyog_cron_action');
 }
/** End Cron Job */

Step 6: Set in config file
define('ALTERNATE_WP_CRON', true);