Wednesday, July 23, 2014

How to Create Stored Procedure in MySql phpmyadmin with Example



How to Create MySql Stored Procedure in PHP

Stored Procedure is a group of Transact SQL statements compiled into a single execution.

For create stored procedure please see below.  Stored procedure reduces database request traffic.

Database Table

employees  table  contains  empname  and  empno

CREATE TABLE employees(id INT PRIMARY KEY AUTO_INCREMENT,
empno VARCHAR(50) UNIQUE, empname VARCHAR(50));          

connection.php
</?php

$con = mysql_connect(“localhost”, “root”, “root”);
mysql_select_db(“storedprocedure”, $con);

?>

showresult.php (Simple fetch data from database)
</?php

include(“connection.php”);

$query = “select empno, empname from employees”;
$result = mysql_query($query);

while($data = mysql_fetch_array($result))
{
                echo $data[‘empno’].’ - ‘.$data[‘empname’].’’;
}

?>

Create Stored Procedure

We are going to create stored procedures that run on our database server.
Stored Procedure name empNoName(). Just like SQL statements.

DELIMITER //
CREATE PROCEDURE empNoName()
SELECT empno, empname from employees;


Call Stored Procedure

showresult.php ( With stored procedures )
</?php

include(“connection.php”);

$query = “CALL empNoName()”;
$result = mysql_query($query);

While($data = mysql_fetch_array($result))
{
                echo $data[‘empno’].’ – ‘.$data[‘empname’];
}

?>

Create Stored Procedure for Input

We can create stored Procedure from 2 types

      1.       1st type
Insert procedure IN – Input, name and datatype.

DELIMITER //
CREATE PROCEDURE insert(IN empno VARCHAR(50), IN empname varchar(50))

INSERT INTO employees(empno, empname) values (empno, empname);

      2.       2nd type

DELIMITER //
CREATE PROCEDURE insert(IN empno varchar(50), IN empname varchar(50))

BEGIN

SET @empno=empno;
SET @empname=empname;

PREPARE STMT FROM
“INSERT INTO user(empno, empname) VALUES (?,?)”;

EXECUTE STMT USING @empno, @empname

END

Insert.php
Include(“connection.php”);
$empno = 11;
$empname = “Kamran”;
$query = “CALL insert(‘$empno’, ‘$empname’)”;
$result = mysql_query($query);

?>


Monday, October 21, 2013

Cron Job Configuration Setting Guide



Cron Job Configuration Guide

 

Cron Jobs basic setup via Cpanel.

Cron Job is use to run a piece of code on certain time interval. It can done by adding following line via cpanel->Cron Jobs:
/usr/local/bin/php /home/your-site-root-dir/public_html/cron-file.php
Wget Method
* * * * *   wget –q –O- ‘http://www.domain.com/cron.php’ >/dev/null
Note: Cron commands depend on the server configuration.

 

Cron Jobs setup via SSH

-> Login to server via SSH
-> Run cd [path-homedir] command for enter the root folder
-> Run password command
-> You will see the path for root folder (eg. /home/yoursitename/public_html)
-> Run which php
-> You see path to PHP (eg. /usr/local/bin/php)
-> Run crontab –e command
-> It will open crontab file editor
-> Make changes to this file, press I key on keyboard for insert/write mode

Monday, February 6, 2012

How to make a triangle in PHP

<\?php
for ($size = 1; $size <= 5; $size++)
{
for ($j = 1; $j <= 5 -$size; $j++)
{
echo "  ";
}
for ($j = 1; $j <= 2*$size - 1; $j++)
{
echo("*");
}
echo "<\br>";
}

?>

Friday, October 14, 2011

import csv data to mysql using php

We can import data of CSV into MYSQL via PHP using fgetcsv() function along with some file handling functions. These codes help you to import data from csv file using PHP.



Create Table in bellow formate
CREATE TABLE `users` (
  `id` int(11) NOT NULL auto_increment,
  `first` text,
  `middle` text,
  `last` text,
  `email` text,
  PRIMARY KEY  (`id`)
);

Save Bellow Code in import.php file
<\?php
$con = mysql_connect("HostName", "DataBaseUserName", "DataBasePassword");
mysql_select_db("DataBaseName");

if(isset($_POST['submit']))
{
      $fileExt = $_FILES['importData']['name'];
      $chkExt = explode(".",$fileExt);
      if(strtolower($chkExt[1]) == "csv")
      {
            $fileName = $_FILES['importData']['tmp_name'];
            $handle = fopen($fileName, "r");
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
            {
                   $sql = "INSERT into users(first, middle, last, email) values('".addslashes($data[0])."', '".addslashes($data[1])."', '".addslashes($data[2])."', '".addslashes($data[3])."')";
                   mysql_query($sql) or die(mysql_error());
            }
            fclose($handle);
            echo "Successfully Imported";
      }else{
            echo "Invalid File";
      }
}
?>

<\form action='' method='post' enctype="multipart/form-data">
                Import File : <\input type="file" name='importData' size='20'>
                <\input type='submit' name='submit' value='Submit'>
<\/form>


Note:- Remove "\" from html tags and php opening tags

Saturday, May 21, 2011

birth date to year calculation in php

Note:- If you want to change formate of date for example YYYY-MM-DD to MM-DD-YYYY then change in list() function parametter and pass same formate parameter end of birthday function.

<\?php
function birthday($birthday)
{
    list($year,$month,$day) = explode("-",$birthday);

    //list($day,$month,$year) = explode("-",$birthday);

    $year_diff = date("Y") - $year;
    $month_diff = date("m") - $month;
    $day_diff = date("d") - $day;
   
    if ($month_diff < 0)
    {
        $year_diff--;
    }
    elseif (($month_diff==0) && ($day_diff < 0))
    {
        $year_diff--;
    }
    return $year_diff;
}

//echo birthday("YYYY-MM-DD");

echo birthday("1982-11-10");

//echo birthday("11-01-1985");
?>

Tuesday, May 17, 2011

multidimensional array sorting in php

Note:- In this post I am sorting multidimensional array by first name if you want to sort by other field then remove first_name and write other field in
array_sort_by_column($people, 'first_name');
Note :- Remove "\" from all places I have added "\" because blogger posting not supported html tags and php opening tag

<\?php

$people = array(
    1 => array(
        'id' => 1,
        'first_name' => 'Kamran',
        'surname' => 'Ahmad',
        'age' => 25,
        'sex' => 'm'
    ),
    2 => array(
        'id' => 2,
        'first_name' => 'Adam',
        'surname' => 'Smith',
        'age' => 18,
        'sex' => 'm'
    ),
    3 => array(
        'id' => 3,
        'first_name' => 'Joe',
        'surname' => 'Bloggs',
        'age' => 23,
        'sex' => 'm'
    ),
    4 => array(
        'id' => 4,
        'first_name' => 'Amy',
        'surname' => 'Jones',
        'age' => 21,
        'sex' => 'f'
    )
);

function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}

array_sort_by_column($people, 'first_name');
?>
<\table width="500px" cellpadding="0" cellspacing="0" border="1">
    <\tr>
        <\td height="30px" align="center"><\b>ID<\/td>
        <\td height="30px" align="center"><\b>First name<\/b><\/td>
        <\td height="30px" align="center"><\b>Surname<\/b><\/td>
        <\td height="30px" align="center"><\b>Age<\/b><\/td>
        <\td height="30px" align="center"><\b>Sex<\/b><\/td>
  
foreach($people as $peo)
{
    echo "<\tr>";
    echo "<\td height='30px' align='center'>".$peo['id']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['first_name']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['surname']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['age']."<\/td>";
    echo "<\td height='30px' align='center'>".$peo['sex']."<\/td>";
    echo "<\/tr>";
}

?>

<\/table>

Thursday, May 5, 2011

export data from mysql database table in csv file using php

In this post we export data from mysql database table in csv file formate using php.

Note : Save bellow file as name  csvfile.php

<\?php
$host = 'localhost'; // MySql DataBase Host Name
$db = 'databasename'; // MySql DataBase Name
$user = 'root'; // MySql DataBase UserName
$pass = ''; // MySql DataBase Password

// Connect to the database
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db);

require 'exportcsv.php';
$table="TableName"; // Table Name that you want to export in csv file from mysql database.

exportMysqlToCsv($table);
?>



Note: Save bellow file as name  exportcsv.php



<\?php
function exportMysqlToCsv($table, $filename = 'csvfilename.csv')
{
    $csv_terminated = "\n";
    $csv_separator = ",";
    $csv_enclosed = '"';
    $csv_escaped = "\\";

    $sql_query = "select * from $table";
    $result = mysql_query($sql_query);
    $fields_cnt = mysql_num_fields($result);
  
    $schema_insert = '';
    for ($i = 0; $i < $fields_cnt; $i++)
    {
        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
        $schema_insert .= $l;
        $schema_insert .= $csv_separator;
    } // end for
    $out = trim(substr($schema_insert, 0, -1));
    $out .= $csv_terminated;
    // Format the data
    while ($row = mysql_fetch_array($result))
    {
        $schema_insert = '';
        for ($j = 0; $j < $fields_cnt; $j++)
        {
            if ($row[$j] == '0' || $row[$j] != '')
            {
                if ($csv_enclosed == '')
                {
                    $schema_insert .= $row[$j];
                }
                else
                {
                    $schema_insert .= $csv_enclosed .
                    str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
                }
            }
            else
            {
                $schema_insert .= '';
            }
            if ($j < $fields_cnt - 1)
            {
                $schema_insert .= $csv_separator;
            }
        } // end for
        $out .= $schema_insert;
        $out .= $csv_terminated;
    } // end while
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: " . strlen($out));
    // Output to browser with appropriate mime type, you choose ;)
    header("Content-type: text/x-csv");
    //header("Content-type: text/csv");
    //header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename=$filename");
    echo $out;
    exit;
}
?>