Test credentials for testing Paytm

  1. MID:DIY12386817555501617
  2. Merchant Key:bKMfNxPPf_QdZppa
  3. WEBSITE: 

for WEB: DIYtestingweb

for WAP: DIYtestingwap

  1. Channel id:WEB/WAP
  2. Industry type id:Retail

The 5 credentials shared above are required to post a valid transaction request on Paytm’s Sandbox servers.

You can access our Merchant Panel for seeing your transaction history and performing other operations:

After successfully initiating a transaction request, you can login to the test Wallet below & complete sample transactions :

Mobile Number : 7777777777
Password : Paytm12345
OTP : 489871

This test wallet is topped-up to a balance of 7000 Rs. every 5 minutes.

After multiple wrong login attempts, this account may automatically get locked. In that case, please comment below and we’ll get it unlocked.

For conducting test transactions using Debit/Credit card, you can use your own card details. No money will be deducted from your card and you will be able to test the payment flow end to end.

 

NOTE :

  1. Refer the link below to download the plugin and utility kit as per your requirement.

http://paywithpaytm.com/developer/

  1. API documentation –

http://paywithpaytm.com/developer/paytm_api_doc/

  1. Mobile SDK documentation –

http://paywithpaytm.com/developer/paytm_sdk_doc/

  1. Redirection: Once the transaction is completed you will be redirected to :

http://paywithpaytm.com/developer/

  1. You can perform a STATUS QUERY to know the status of your transactions:

https://pguat.paytm.com/oltp/HANDLER_INTERNAL/TXNSTATUS?JsonData={“MID”:”xxxxxxxxxxxxxxxxxxx”,”ORDERID”:”xxxxxxxxxxxx”}

 

Reference::-http://paywithpaytm.com/developer/discussion/topic/sandbox-test-credentials-for-testing-paytm-solutions/

Create Slug using Helper

   /**
* Generate a unique slug.
* If it already exists, a number suffix will be appended.
* It probably works only with MySQL.
*
*
* @param Illuminate\Database\Eloquent\Model $model
* @param string $value
* @return string
*/
public static function getUniqueSlug($model, $value) {
$slug = \Illuminate\Support\Str::slug(trim($value));
$slugCount = count($model->whereRaw(“slug REGEXP ‘^{$slug}(-[0-9]+)?$’ and id != ‘{$model->id}'”)->get());

return ($slugCount > 0) ? “{$slug}-{$slugCount}” : $slug;
}

 

 

TO create Slug

I am create slug for cms Pages

Firstly Create Cms Model Object.

$cmsObj = new Cms();

 

$slug = BasicFunction::getUniqueSlug($cmsObj, $request->title);

 

 

cakephp authentication

cakephp authentication

appconrtoller:

class AppController extends Controller {
/**
* Helpers will be used
*
* @var array
*/
public $helpers = array(‘Html’, ‘Form’, ‘Session’, ‘Text’, ‘Js’); //, ‘GeneralFunctions’
/**
* Components will be used
*
* @var array
*/
public $components = array(‘Session’, ‘RequestHandler’, ‘Paginator’, ‘Auth’, ‘Cookie’, ‘Email’);

function beforeFilter() {
parent::beforeFilter();

$this->Auth->authenticate = array(‘all’ => array(‘scope’ => array(‘User.user_type’ => array(‘user’), ‘User.is_blocked’ => 0,’User.status’ => 1)), ‘Form’ => array(‘fields’ => array(‘username’ => ’email’, ‘password’ => ‘password’)));
$this->Auth->loginAction =  array(‘plugin’ => false, ‘controller’ => ‘users’, ‘action’ => ‘login’);
$this->sessiondata = ‘Auth.User’;
$loginRedirect =  ‘dashboard’;
$this->Auth->loginRedirect = array(‘plugin’ => false, ‘controller’ => ‘users’, ‘action’ => ‘dashboard’);

}

 

}

user conroller

class UsersController extends UsersAppController {

public $uses = array(‘Users.User’);
public $helpers = array(‘Html’, ‘Form’);
public $components = array(‘Auth’);

function beforeFilter() {
parent::beforeFilter();
$this->set(‘model’, $this->modelClass);

$this->Auth->allow(‘register’, ‘login’,’admin_login’);

}

function login() {

if($this->Auth->loggedIn()){

$this->redirect(array(‘plugin’=>’users’,’controller’=>’users’,’action’=>’dashboard’));

}

if (!empty($this->data)) {

$this->{$this->modelClass}->set($this->data);
if ($this->{$this->modelClass}->loginvalidation()) {

if ($this->Auth->login()) {

return $this->redirect($this->Auth->redirect());
}
} else {

}
} else {

}
}

function dashboard(){

}

function logout(){
return $this->redirect($this->Auth->logout());

}

}

 

Usser model

 

<?php

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* CakePHP User
* @author vijayraj
*/
App::uses(‘AppModel’, ‘Model’);

class User extends AppModel {

public $uses = ‘User’;

//validation for login form

function loginvalidation() {
$validation1 = array(
’email’ => array(
’empty’ => array(
‘rule’ => ‘notEmpty’,
‘message’ => ‘error_name’
),
‘valid’=>array(
‘rule’=>’email’,
‘message’=>’please enter valid email’

),

),

‘password’ => array(
’empty’ => array(
‘rule’ => ‘notEmpty’,
‘message’ => ‘error_name’
)
),

);
$this->validate = $validation1;
return $this->validates();
}

}

 

login.ctp

 
<div class=”row”>

<?php echo $this->form->create($model,array(‘class’=>’form-horizontal’)); ?>
<div class=”form-group”>

<?php echo $this->Form->label($model.’.email’,__d(‘default’,’email’),array(‘class’=>’col-sm-2 control-label’));  ?>
<div class=”col-sm-10″>

<?php echo  $this->Form->text($model.’.email’,array(‘class’=>’form-control’,’label’=>false,’required’=>false,’error’=>false)); ?>
<?php  echo $this->form->error($model.’.email’); ?>
</div>
</div>
<div class=”form-group”>
<?php echo $this->Form->label($model.’.password’,__d(‘default’,’password’),array(‘class’=>’col-sm-2 control-label’));  ?>
<div class=”col-sm-10″>

<?php echo  $this->Form->password($model.’.password’,array(‘class’=>’form-control’,’label’=>false,’required’=>false,’error’=>false)); ?>
<?php echo $this->form->error($model.’.password’); ?>
</div>
</div>

<div class=”form-group”>
<div class=”col-sm-offset-2 col-sm-10″>

<?php echo  $this->Form->submit(‘Sign in’,array(‘class’=>’btn btn-default’)); ?>
</div>
</div>
<?php echo  $this->Form->end(); ?>

</div>

 

 

encryption decryption method in php

class Encryption {
var $skey = “d7ceb4c8102153ba-%^&*#@!#@%$#^&^$%%@$$$544d30008ed7e738″; // you can change it

public  function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array(‘+’,’/’,’=’),array(‘-‘,’_’,”),$data);
return $data;
}

public function safe_b64decode($string) {
$data = str_replace(array(‘-‘,’_’),array(‘+’,’/’),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr(‘====’, $mod4);
}
return base64_decode($data);
}

public  function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}

public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return trim($decrypttext);
}
}
$str = “vijayraj”;

$converter = new Encryption;
$encoded = $converter->encode($str );
$decoded = $converter->decode($encoded);

echo “$encoded<p>$decoded”;

Best SQL Excercise

Simple SELECTs

Introduction to the Northwind Database

The Northwind database is a sample database used by Microsoft to demonstrate the features of some of its products, including SQL Server and Microsoft Access. The database contains the sales data for Northwind Traders, a fictitious specialty foods export-import company.

Although the code taught in this class is not specific to Microsoft products, we use the Northwind database for many of our examples because many people are already familiar with it and because there are many resources for related learning that make use of the same database.

The diagram below shows the table structure of the Northwind database.

Presentation2

The Northwind database has additional tables, but we will only be using the ones shown above. In this lesson, we will explore some of these tables

Comments

The standard SQL comment is two hyphens (–).
Code Sample

— Single-line comment

/*

Multi-line comment used in:

-SQL Server

-Oracle

-MySQL

*/

Whitespace and Semi-colons

Whitespace is ignored in SQL statements. Multiple statements are separated with semi-colons. The two statements in the sample below are equally valid.

Code Sample SimpleSelects

SELECT * FROM Employees;

SELECT *
FROM Employees;

Case Sensitivity

SQL is not case sensitive. It is common practice to write reserved words in all capital letters. User-defined names, such as table names and column names may or may not be case sensitive depending on the operating system used.

SELECTing All Columns in All Rows

--Retrieve all columns in the Region table
SELECT *
FROM Region;

 

SELECTing Specific Columns

/*
Select the FirstName and LastName columns from the Employees table.
*/
SELECT FirstName, LastName
FROM Employees;

 

Exercise: SELECTing Specific Columns

  1. Select CategoryName and Description from the Categories table.
  2. Select ContactName, CompanyName, ContactTitle and Phone from the Customers table.
  3. Select EmployeeID, Title, FirstName, LastName, and Region from the Employees table.
  4. Select RegionID and RegionDescription from the Region table.
  5. Select CompanyName, Fax, Phone and HomePage from the Suppliers table.

Sorting Records

/*

Select the FirstName and LastName columns from the Employees table.

Sort by LastName.

*/

SELECT FirstName, LastName

FROM Employees ORDER BY LastName;

Sorting By Multiple Columns

/*
Select the Title, FirstName and LastName columns from the Employees table.
Sort first by Title and then by LastName.
*/

SELECT Title, FirstName, LastName
FROM Employees
ORDER BY Title, LastName;

Sorting By Column Position

/*

Select the Title, FirstName and LastName columns from the Employees table.

Sort first by Title (position 1) and then by LastName (position 3).

*/

SELECT Title, FirstName, LastName FROM Employees ORDER BY 1,3;

Ascending and Descending Sorts

/*
 Select the Title, FirstName and LastName columns from the Employees table.
 Sort first by Title in ascending order and then by LastName 
 in descending order.
*/

SELECT Title, FirstName, LastName
FROM Employees
ORDER BY Title ASC, LastName DESC;

Exercise: Sorting Results
Duration: 5 to 15 minutes.

  1. Select CategoryName and Description from the Categories table sorted by CategoryName.
  2. Select ContactName, CompanyName, ContactTitle, and Phone from the Customers table sorted by Phone.
  3. Create a report showing employees’ first and last names and hire dates sorted from newest to oldest employee.
  4. Create a report showing Northwind’s orders sorted by Freight from most expensive to cheapest. Show OrderID, OrderDate, ShippedDate, CustomerID, and Freight.
  5. Select CompanyName, Fax, Phone, HomePage and Country from the Suppliers table sorted by Country in descending order and then by CompanyName in ascending order.

The WHERE Clause and Operator Symbols

/*
Create a report showing the title and the first and last name
of all sales representatives.
*/

SELECT Title, FirstName, LastName
FROM Employees
WHERE Title = 'Sales Representative';

Checking for Inequality

/*

Create a report showing the first and last name of all employees

excluding sales representatives.

*/

SELECT FirstName, LastName

FROM Employees WHERE Title <> ‘Sales Representative’;

Exercise: Using the WHERE clause to check for equality or inequality
Duration: 5 to 15 minutes.

  1. Create a report showing all the company names and contact names of Northwind’s customers in Buenos Aires.
  2. Create a report showing the product name, unit price and quantity per unit of all products that are out of stock.
  3. Create a report showing the order date, shipped date, customer id, and freight of all orders placed on May 19, 1997.
  4. Create a report showing the first name, last name, and country of all employees not in the United States.

Checking for Greater or Less Than

/*

Create a report showing the first and last name of all employees whose

last names start with a letter in the last half of the alphabet.

*/

SELECT FirstName, LastName

FROM Employees WHERE LastName >= ‘N’;

Exercise: Using the WHERE clause to check for greater or less than
Duration: 5 to 15 minutes.

  1. Create a report that shows the employee id, order id, customer id, required date, and shipped date of all orders that were shipped later than they were required.
  2. Create a report that shows the city, company name, and contact name of all customers who are in cities that begin with “A” or “B.”
  3. Create a report that shows all orders that have a freight cost of more than $500.00.
  4. Create a report that shows the product name, units in stock, units on order, and reorder level of all products that are up for reorder.

Checking for NULL

/*

Create a report showing the first and last names of

all employees whose region is unspecified.

*/

SELECT FirstName, LastName

FROM Employees WHERE Region IS NULL;

/*
Create a report showing the first and last names of all
employees who have a region specified.
*/

SELECT FirstName, LastName
FROM Employees
WHERE Region IS NOT NULL;

Exercise: Checking for NULL
Duration: 5 to 15 minutes.

  1. Create a report that shows the company name, contact name and fax number of all customers that have a fax number.
  2. Create a report that shows the first and last name of all employees who do not report to anybody.

WHERE and ORDER BY

/*
Create a report showing the first and last name of all employees whose 
last names start with a letter in the last half of the alphabet.
Sort by LastName in descending order.
*/

SELECT FirstName, LastName
FROM Employees
WHERE LastName >= 'N'
ORDER BY LastName DESC;

Exercise: Using WHERE and ORDER BY Together
Duration: 5 to 15 minutes.

  1. Create a report that shows the company name, contact name and fax number of all customers that have a fax number. Sort by company name.
  2. Create a report that shows the city, company name, and contact name of all customers who are in cities that begin with “A” or “B.” Sort by contact name in descending order.

The WHERE Clause and Operator Words

The BETWEEN Operator

/*

Create a report showing the first and last name of all employees

whose last names start with a letter between “J” and “M”.

*/

SELECT FirstName, LastName

FROM Employees

WHERE LastName BETWEEN ‘J’ AND ‘M’;

— The above SELECT statement is the same as the one below.

SELECT FirstName, LastName

FROM Employees WHERE LastName >= ‘J’ AND LastName <= ‘M’;

 

The IN Operator

/*
Create a report showing the title of courtesy and the first and
last name of all employees whose title of courtesy is "Mrs." or "Ms.". 
*/

SELECT TitleOfCourtesy, FirstName, LastName
FROM Employees
WHERE TitleOfCourtesy IN ('Ms.','Mrs.');

-- The above SELECT statement is the same as the one below

SELECT TitleOfCourtesy, FirstName, LastName
FROM Employees
WHERE TitleOfCourtesy = 'Ms.' OR TitleOfCourtesy = 'Mrs.';

 

The LIKE Operator

/*
Create a report showing the title of courtesy and the first
and last name of all employees whose title of courtesy begins with "M". 
*/

SELECT TitleOfCourtesy, FirstName, LastName
FROM Employees
WHERE TitleOfCourtesy LIKE 'M%';

 

The Underscore (_)

/*
Create a report showing the title of courtesy and the first and
last name of all employees whose title of courtesy begins with "M" and
is followed by any character and a period (.).
*/

SELECT TitleOfCourtesy, FirstName, LastName
FROM Employees
WHERE TitleOfCourtesy LIKE 'M_.';

 

Wildcards and Performance: Using wildcards can slow down performance, especially if they are used at the beginning of a pattern. You should use them sparingly.

The NOT Operator

/*

Create a report showing the title of courtesy and the first and last name

of all employees whose title of courtesy is not “Ms.” or “Mrs.”.

*/

SELECT TitleOfCourtesy, FirstName, LastName

FROM Employees WHERE NOT TitleOfCourtesy IN (‘Ms.’,’Mrs.’);


Exercise: More SELECTs with WHERE

Duration: 5 to 15 minutes.

  1. Create a report that shows the first and last names and birth date of all employees born in the 1950s.
  2. Create a report that shows the product name and supplier id for all products supplied by Exotic Liquids, Grandma Kelly’s Homestead, and Tokyo Traders. Hint: you will need to first do a separate SELECT on the Suppliers table to find the supplier ids of these three companies.
  3. Create a report that shows the shipping postal code, order id, and order date for all orders with a ship postal code beginning with “02389”.
  4. Create a report that shows the contact name and title and the company name for all customers whose contact title does not contain the word “Sales”.

Checking Multiple Conditions

AND

/*
Create a report showing the first and last name of all
sales representatives whose title of courtesy is "Mr.".
*/

SELECT FirstName, LastName
FROM Employees
WHERE Title = 'Sales Representative'
 AND TitleOfCourtesy = 'Mr.';


OR

/*
 Create a report showing the first and last name and the city of all 
 employees who are from Seattle or Redmond.
*/

SELECT FirstName, LastName, City
FROM Employees
WHERE City = 'Seattle' OR City = 'Redmond';

 

Order of Evaluation: By default, SQL processes AND operators before it processes OR operators. To illustrate how this works, take a look at the following example.

/*

Create a report showing the first and last name of all sales

representatives who are from Seattle or Redmond.

*/

SELECT FirstName, LastName, City, Title

FROM Employees

WHERE City = ‘Seattle’ OR City = ‘Redmond’ AND Title = ‘Sales Representative’;

 

/*
 Create a report showing the first and last name of all sales 
 representatives who are from Seattle or Redmond.
*/

SELECT FirstName, LastName, City, Title
FROM Employees
WHERE (City = 'Seattle' OR City = 'Redmond')
 AND Title = 'Sales Representative';

The parentheses specify that the OR portion of the clause should be evaluated first.

Exercise: Writing SELECTs with Multiple Conditions
Duration: 5 to 15 minutes

  1. Create a report that shows the first and last names and cities of employees from cities other than Seattle in the state of Washington.
  2. Create a report that shows the company name, contact title, city and country of all customers in Mexico or in any city in Spain except Madrid.

Advance SELECTs

Calculated Fields

Concatenation

-- Select the full name of all employees. SQL SERVER.

SELECT FirstName + ' ' + LastName
FROM Employees;

Mathematical Calculations

/*
If the cost of freight is greater than or equal to $500.00,
it will now be taxed by 10%. Create a report that shows the
order id, freight cost, freight cost with this tax for all
orders of $500 or more.
*/

SELECT OrderID, Freight, Freight * 1.1
FROM Orders
WHERE Freight >= 500;

Aliases

SELECT OrderID, Freight, Freight * 1.1 AS FreightTotal
FROM Orders
WHERE Freight >= 500;

Exercise: Calculating Fields

Duration: 10 to 20 minutes.

  1. Create a report that shows the unit price, quantity, discount, and the calculated total price using these three fields.
    • Note for SQL Server users only: You will be using the Order Details table. Because this table name has a space in it, you will need to put it in double quotes in the FROM clause (e.g, FROM “Order Details”).
  2. Write a SELECT statement that outputs the following.

Aggregate Functions and Grouping

Aggregate Functions

-- Find the Number of Employees
SELECT COUNT(*) AS NumEmployees
FROM Employees;

-- Find the Total Number of Units Ordered of Product ID 3
/******************************
SQL Server
******************************/
SELECT SUM(Quantity) AS TotalUnits
FROM "Order Details"
WHERE ProductID=3;

-- Find the Average Unit Price of Products
SELECT AVG(UnitPrice) AS AveragePrice
FROM Products;

-- Find the Earliest and Latest Dates of Hire
SELECT MIN(HireDate) AS FirstHireDate,
 MAX(HireDate) AS LastHireDate
FROM Employees;

GROUP BY

--Retrieve the number of employees in each city

SELECT City, COUNT(EmployeeID) AS NumEmployees
FROM Employees
GROUP BY City;

HAVING

/*
 Retrieve the number of employees in each city 
 in which there are at least 2 employees.
*/

SELECT City, COUNT(EmployeeID) AS NumEmployees
FROM Employees
GROUP BY City
HAVING COUNT(EmployeeID) > 1;

Order of Clauses

  1. SELECT
  2. FROM
  3. WHERE
  4. GROUP BY
  5. HAVING
  6. ORDER BY

/*

Find the number of sales representatives in each city that contains

at least 2 sales representatives. Order by the number of employees.

*/

SELECT City, COUNT(EmployeeID) AS NumEmployees

FROM Employees

WHERE Title = ‘Sales Representative’

GROUP BY City

HAVING COUNT(EmployeeID) > 1 ORDER BY NumEmployees;

Exercise: Working with Aggregate Functions
Duration: 10 to 20 minutes.
1. Create a report that returns the following from the Order_Details table. The report should only return rows for which TotalUnits is less than 200.

2. Create a report that returns the following from the Products table. The report should only return rows for which the average unit price of a product is greater than 70.

3. Create a report that returns the following from the Orders table. NumOrders represents the number of orders placed by a certain customer. Only return rows where NumOrders is greater than 15.

Selecting Distinct Records

/*
Find all the distinct cities in which Northwind has employees.
*/

SELECT DISTINCT City
FROM Employees
ORDER BY City

/*
Find out in how many different cities Northwind has employees.
*/

SELECT COUNT(DISTINCT City) AS NumCities
FROM Employees

Built-in Data Manipulation Functions

Common Math Functions

/*
Select freight as is and
freight rounded to the first decimal (e.g, 1.150 becomes 1.200)
from the Orders tables
*/

SELECT Freight, ROUND(Freight,1)  AS ApproxFreight
FROM Orders;

 

/*

Select the unit price as is and

unit price as a decimal with 2 places to the right of the decimal point

from the Products tables

*/

/******************************

SQL Server and MySQL

******************************/

SELECT UnitPrice, CAST(UnitPrice AS Decimal(8,2)) FROM Products;

Common String Functions

/*

Select first and last name from employees in all uppercase letters

*/

SELECT UPPER(FirstName), UPPER(LastName) FROM Employees;

-- Select the first 10 characters of each customer's address

/******************************
SQL Server and MySQL
******************************/
SELECT SUBSTRING(Address,1,10)
FROM Customers;

/******************************
Oracle
******************************/
SELECT SUBSTR(Address,1,10)
FROM Customers;

Common Date Functions

-- Find the hiring age of each employee

/******************************
SQL Server
******************************/
SELECT LastName, BirthDate, HireDate, DATEDIFF(year,BirthDate,HireDate) AS HireAge
FROM Employees
ORDER BY HireAge;
-- Find the Birth month for every employee

/******************************
SQL Server
******************************/
SELECT FirstName, LastName, DATENAME(month,BirthDate) AS BirthMonth
FROM Employees
ORDER BY DATEPART(month,BirthDate);

Subqueries, Joins and Unions

/*
Find the CustomerID of the company that placed order 10290.
*/

SELECT CustomerID
FROM Orders
WHERE OrderID = 10290;
-- Find the name of the company that placed order 10290.

SELECT CompanyName
FROM Customers
WHERE CustomerID = (SELECT CustomerID
   FROM Orders
   WHERE OrderID = 10290);

Exercise: Subqueries
Create a report that shows all products by name that are in the Seafood category.
Create a report that shows all companies by name that sell products in CategoryID 8.
Create a report that shows all companies by name that sell products in the Seafood category.

-- Create a report showing employee orders.

SELECT Employees.EmployeeID, Employees.FirstName,
 Employees.LastName, Orders.OrderID, Orders.OrderDate
FROM Employees JOIN Orders ON
 (Employees.EmployeeID = Orders.EmployeeID)
ORDER BY Orders.OrderDate;
-- Create a report showing employee orders using Aliases.

SELECT e.EmployeeID, e.FirstName, e.LastName,
 o.OrderID, o.OrderDate
FROM Employees e JOIN Orders o ON
 (e.EmployeeID = o.EmployeeID)
ORDER BY o.OrderDate;
/*
 Create a report that shows the number of
 employees and customers from each city that has employees in it.
*/

SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
 COUNT(DISTINCT c.CustomerID) AS numCompanies,
 e.City, c.City
FROM Employees e JOIN Customers c ON
 (e.City = c.City)
GROUP BY e.City, c.City
ORDER BY numEmployees DESC;

/*

Create a report that shows the number of

employees and customers from each city that has employees in it.

*/

SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,

COUNT(DISTINCT c.CustomerID) AS numCompanies,

e.City, c.City

FROM Employees e LEFT JOIN Customers c ON

(e.City = c.City)

GROUP BY e.City, c.City ORDER BY numEmployees DESC;

/*

Create a report that shows the number of

employees and customers from each city that has customers in it.

*/

SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,

COUNT(DISTINCT c.CustomerID) AS numCompanies,

e.City, c.City

FROM Employees e RIGHT JOIN Customers c ON

(e.City = c.City)

GROUP BY e.City, c.City ORDER BY numEmployees DESC;

/*
 Create a report that shows the number of
 employees and customers from each city.

 Note that MySQL 5.x does NOT support full outer joins.
*/

SELECT COUNT(DISTINCT e.EmployeeID) AS numEmployees,
 COUNT(DISTINCT c.CustomerID) AS numCompanies,
 e.City, c.City
FROM Employees e FULL JOIN Customers c ON
 (e.City = c.City)
GROUP BY e.City, c.City
ORDER BY numEmployees DESC;
/*
Get the phone numbers of all shippers, customers, and suppliers
*/

SELECT CompanyName, Phone
FROM Shippers
 UNION
SELECT CompanyName, Phone
FROM Customers
 UNION
SELECT CompanyName, Phone
FROM Suppliers
ORDER BY CompanyName;

Using CASE

/*
Create a report showing the customer ID and company name,
employee id, firstname and lastname, and the order id
and a conditional column called "Shipped" that displays "On Time"
if the order was shipped on time and "Late" if the order was shipped late.
*/SELECT c.CustomerID, c.CompanyName, e.EmployeeID, e.FirstName, e.LastName, OrderID,
 (CASE
  WHEN ShippedDate < RequiredDate
   THEN 'On Time'
   ELSE 'Late'
   END) AS Shipped
FROM Orders o
 JOIN Employees e ON (e.EmployeeID = o.EmployeeID)
 JOIN Customers c ON (c.CustomerID = o.CustomerID)
ORDER BY Shipped;

Remove “index.php” in codeigniter’s path

If you are using Apache place a .htaccess file in your root web directory containing the following:

RewriteEngine On
RewriteBase /code_work/

RewriteRule ^code_work/?$ index.php/admin/ [L]
RewriteRule ^code_work/([^.]+)/?$ index.php/admin/$1 [L]

RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?/$1 [L]
 for admin penal:-

in rout.php

$route[‘admin’]=”admin/home”;
$route[“admin/(:any)”]=”admin/$1″;

Joins

Sometimes you required the data from more than one table. When you select the data from more than one table this is known as Joining. A join is a SQL query that is used to select the data from more than one table or views. When you define multiple tables or views in the FROM clause of a query the MySQL performs a join that linking the rows from multiple tables together.

Types of Joins :

  • INNER Joins
  • OUTER Joins
  • SELF Joins

We are going to describe you the Join with the help of following two tables :

mysql> SELECT * FROM Client;

+——+—————+———-+

| C_ID | Name          | City     |

+——+—————+———-+

| 1    | A K Ltd       | Delhi    |

| 2    | V K Associate | Mumbai   |

| 3    | R K India     | Banglore |

| 4    | R S P Ltd     | Kolkata  |

+——+—————+———-+

4 rows in set (0.00 sec)

mysql> SELECT * FROM Products;

+———+————-+——+

| Prod_ID | Prod_Detail | C_ID |

+———+————-+——+

| 111     | Monitor     | 1    |

| 112     | Processor   | 2    |

| 113     | Keyboard    | 2    |

| 114     | Mouse       | 3    |

| 115     | CPU         | 5    |

+———+————-+——+

5 rows in set (0.00 sec)

INNER Joins

The INNER join is considered as the default Join type. Inner join returns the column values from one row of a table combined with the column values from one row of another table that satisfy the search condition for the join. The general syntax of INNER Join is :
SELECT <column_name1>, <column_name2> FROM <tbl_name> INNER JOIN <tbl_name> ON <join_conditions>

The following example takes all the records from table Client and finds the matching records in table Product. But if no match is found then the record from table Client is not included in the results. But if multiple results are found in table Product with the given condition then one row will be return for each.
Example :

mysql> SELECT * FROM Client

    -> INNER JOIN Products

    -> ON Client.C_ID=Products.C_ID;

+——+—————+———-+———+————-+——+

| C_ID | Name          | City     | Prod_ID | Prod_Detail | C_ID |

+——+—————+———-+———+————-+——+

| 1    | A K Ltd       | Delhi    | 111     | Monitor     | 1    |

| 2    | V K Associate | Mumbai   | 112     | Processor   | 2    |

| 2    | V K Associate | Mumbai   | 113     | Keyboard    | 2    |

| 3    | R K India     | Banglore | 114     | Mouse       | 3    |

+——+—————+———-+———+————-+——+

4 rows in set (0.04 sec)

OUTER Joins

Sometimes when we are performing a Join between the two tables, we need all the records from one table even there is no corresponding record in other table. We can do this with the help of OUTER Join. In other words an OUTER Join returns the all rows that returned by an INNER Join plus all the rows from one table that did not match any row from the other table. Outer Join are divided in two types : LEFT OUTER Join, RIGHT OUTER Join

LEFT OUTER Join

LEFT OUTER Join is used to return all the rows that returned by an INNER Join plus all the rows from first table that did not match with any row from the second table but with the NULL values for each column from second table. The general syntax of LEFT OUTER Join is :
SELECT <column_name1>, <column_name2> FROM <tbl_name> LEFT OUTER JOIN <tbl_name> ON <join_conditions>

In the following example we are selected every row from the Client table which don?t have a match in the Products Table. Example :

mysql> SELECT * FROM CLIENT

    -> LEFT OUTER JOIN Products

    -> ON Client.C_ID=Products.C_ID;

+——+—————+———-+———+————-+——+

| C_ID | Name          | City     | Prod_ID | Prod_Detail | C_ID |

+——+—————+———-+———+————-+——+

| 1    | A K Ltd       | Delhi    | 111     | Monitor     | 1    |

| 2    | V K Associate | Mumbai   | 112     | Processor   | 2    |

| 2    | V K Associate | Mumbai   | 113     | Keyboard    | 2    |

| 3    | R K India     | Banglore | 114     | Mouse       | 3    |

| 4    | R S P Ltd     | Kolkata  | NULL    |             | NULL |

+——+—————+———-+———+————-+——+

5 rows in set (0.00 sec)

In the following example we are using the ORDER BY Clause with the LEFT OUTER Join.

mysql> SELECT * FROM Client

    -> LEFT OUTER JOIN Products

    -> ON Client.C_ID=Products.C_ID

    -> ORDER BY Client.City;

+——+—————+———-+———+————-+——+

| C_ID | Name          | City     | Prod_ID | Prod_Detail | C_ID |

+——+—————+———-+———+————-+——+

| 3    | R K India     | Banglore | 114     | Mouse       | 3    |

| 1    | A K Ltd       | Delhi    | 111     | Monitor     | 1    |

| 4    | R S P Ltd     | Kolkata  | NULL    |             | NULL |

| 2    | V K Associate | Mumbai   | 113     | Keyboard    | 2    |

| 2    | V K Associate | Mumbai   | 112     | Processor   | 2    |

+——+—————+———-+———+————-+——+

5 rows in set (0.08 sec)

In the result of LEFT OUTER Join ” R S P Ltd ” is included even though it has no rows in the Products table.

RIGHT OUTER Join

RIGHT OUTER Join is much same as the LEFT OUTER JOIN. But RIGHT OUTER Join is used to return all the rows that returned by an INNER Join plus all the rows from second table that did not match with any row from the first table but with the NULL values for each column from first table. The general syntax of RIGHT OUTER Join is :
SELECT <column_name1>, <column_name2> FROM <tbl_name> RIGHT OUTER JOIN <tbl_name> ON <join_conditions>

In the following example we are selected every row from the Products table which don?t have a match in the Client Table. Example :

mysql> SELECT * FROM Client

    -> RIGHT OUTER JOIN Products

    -> ON Client.C_ID=Products.C_ID;

+——+—————+———-+———+————-+——+

| C_ID | Name          | City     | Prod_ID | Prod_Detail | C_ID |

+——+—————+———-+———+————-+——+

| 1    | A K Ltd       | Delhi    | 111     | Monitor     | 1    |

| 2    | V K Associate | Mumbai   | 112     | Processor   | 2    |

| 2    | V K Associate | Mumbai   | 113     | Keyboard    | 2    |

| 3    | R K India     | Banglore | 114     | Mouse       | 3    |

| NULL |               |          | 115     | CPU         | 5    |

+——+—————+———-+———+————-+——+

5 rows in set (0.03 sec)

SELF Join

SELF Join means a table can be joined with itself. SELF Join is useful when we want to compare values in a column to other values in the same column. For creating a SELF Join we have to list a table twice in the FROM clause and assign it a different alias each time. For referring the table we have to use this aliases.

The following example provide you the list of those Clients that belongs to same city of C_ID=1.

mysql> SELECT b.C_ID,b.Name,b.City FROM Client a, Client b

    -> WHERE a.City=b.City AND a.C_ID=1;

+——+———-+——-+

| C_ID | Name     | City  |

+——+———-+——-+

| 1    | A K Ltd  | Delhi |

| 5    | A T Ltd  | Delhi |

| 6    | D T Info | Delhi |

+——+———-+——-+

3 rows in set (0.00 sec)

we can write this SELF JOIN Query in Subquery like this also :

mysql> SELECT * FROM Client

    -> WHERE City=(

    -> SELECT City FROM Client

    -> WHERE C_ID=1);

+——+———-+——-+

| C_ID | Name     | City  |

+——+———-+——-+

| 1    | A K Ltd  | Delhi |

| 5    | A T Ltd  | Delhi |

| 6    | D T Info | Delhi |

+——+———-+——-+

3 rows in set (0.03 sec)

 

Database Designing

There are some rules are available for designing the database. These are given below :

  • MySQL use the alpha numeric character .
  • MySQL limited the 64 characters .
  • MySQL use the underscore (_) to separate word.
  • MySQL is entirely lowercase word .
  • MySQL use the plural table name to indicate multiple value store  and singular column names .

MySQL Database Normalization
Normalization is a process that is used in relational database design to organize the data for minimizing the duplication. In normalization, we divide the database in two or more tables and create the relationship between them. After isolate the data we performed some additions, deletions or modifications of a field on only one table, then that can be propagated on the rest of the database through the defined relationships. The main two goals of normalization process are: eliminate the redundancy of data and make sure that the data dependencies (relationship) make sense. By these two goals we can reduce the space that is consumed by the database and ensure that data is logically stored.

First normal Form

The First Normal Form requires the atomic values in each column. Atomic means the set of values are not available with in the column. In other words, in First Normal Form table must have at least one candidate key and make sure the table don?t have any duplicate record. In First Normal Form repeating groups are not allowed, that is no attributes which occur a different number of times on different records

Second normal Form
You can achieve the Second Normal Form only then when your table must meet the First Normal Form with its entire requirement. As you seen the First Normal Form works with only atomicity of data, but Second Normal Form deals with the relationships of tables between composite keys and non-key columns. In Second Normal Form subset of data is removed, and its apply to multiple rows of a table and then place them in separate tables.

Third Normal Form
You can achieve the Third Normal Form only then when your table must meet the Second Normal Form with its entire requirement. In Third Normal Form, all columns must be directly depended on the primary key means remove the column, which is not dependent upon the primary key.

Boyce – Codd Normal Form
You can achieve the Boyce – Codd Normal Form only then when your table must meet the Third Normal Form with its entire requirement. In Boyce – Codd Normal Form every non-trivial functional dependency must be a dependency on a superkey.

Fourth Normal Form
You can achieve the Fourth Normal Form only then when your table must meet the Boyce – Codd Normal Form with its entire requirement. Fourth Normal Form confirmed you that the independent multivalued facts are efficiently and correctly represented in database design.

 

Inner join

Scenario-1: Using the count or sum with inner join query

Table structures:

videos: id, title, description, date_uploaded

categories: id, category_name

votes: id, videoid, vote, date (vote will range between 1 and 5)

Query:
SELECT v.id as vid, v.title, v.description, v.date_uploaded, c.category_name, v2.total, v2.count FROM videos v inner join
categories c inner join (select videoid, sum(vote) as total, count(*) as count from votes group by videoid) v2 on v.category_id=c.id and v2.videoid=v.id and v.featured=1 and v.published=1 order by v.date_uploaded desc;

Resultset:

vid   title  description        date_uploaded            id    category_name   total  count
12    Ford   inauguration  2011-10-07 01:08:22    3    Inauguration        97     31
9      Nano   new car          2011-11-02 03:15:25    2    Automobile        120    38

From the above result set, we can get the percentage of votes for videos as: (total / count) * 20
Note: The above query assumes that you have a record in votes table for each video id in videos table.

Scenario-2: Get the count of videos for each category

Table structures:

videos: id, title, category_id

categories: id, category_name

Query:
SELECT c.id, c.category_name, v.total FROM categories c inner join (select category_id, count(*) as total from videos where published=1 group by category_id) v on c.id=v.category_id group by c.id order by c.category_name;

Result: We can get the total number of videos for each category