Monday, June 11, 2012

Simple Calculator PHP

Simple Calculator PHP

In PHP you may find lot of mathematical  functions.Here, I am not going to cover all of them but very important mathematical fictions are covered with the practical examples in this tutorial.
Calculator interface  is bellow.

Number 1
Number 2
Operation:-AdditionSubtraction

DivisionMultiplication

ModulePower

Random NumberPercentage

Inserting the numbers in to the fields number1 and number2 then clicking operation radio button and pressing calculate you can get the values calculated. Codes for the above calculator is as bellow.

<table bgcolor=#d38a2a>
<form name="calc" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<tr bgcolor=#ffffff><td>Number 1</td><td><input type="text" name="value1"><td rowspan=2 align="center"><img src="cal.png"></td></tr>
<tr bgcolor=#ffffff><td>Number 2</td><td><input type="text" name="value2"></td></tr>
<tr bgcolor=#ffffff><td>Operation:-</td><td><input type="radio" name="oper" value="add">Addition</td><td><input type="radio" name="oper" value="subtract">Subtraction</td></tr>
<tr bgcolor=#ffffff><td>&nbsp;</td><td><input type="radio" name="oper" value="divide">Division</td><td><input type="radio" name="oper" value="multify">Multipication</td></tr>
<tr bgcolor=#ffffff><td>&nbsp;</td><td><input type="radio" name="oper" value="mod">Module</td><td><input type="radio" name="oper" value="pow">Power</td></tr>
<tr bgcolor=#ffffff><td>&nbsp;</td><td><input type="radio" name="oper" value="rad">Random Number</td><td><input type="radio" name="oper" value="per">Percentage</input></td></tr>
<tr bgcolor=#ffffff><td colspan=3 align="right"><input type="submit" value="Calculate"></td></tr>
</form>
</table>
<?php
$number1=$_POST['value1'];
$number2=$_POST['value2'];
$oper=$_POST['oper'];

if($oper=='add'){

$result=$number1+$number2;

echo "Result is".$result;
}
else if($oper=='subtract'){
$result=$number1-$number2;
echo "Result is".$result;
}
else if($oper=='divide'){
$result=$number1/$number2;
echo "Result is".$result;
}
else if($oper=='multify'){
$result=$number1*$number2;
echo "Result is".$result;
}
else if($oper=='mod'){
echo fmod($number1,$number2);
}
else if($oper=='pow'){
echo pow($number1,$number2);
}
else if($oper=='rad'){
echo rand($number1,$number2);
}
else if($oper=='per'){
$number3=$number2/100;
$result=$number1*$number3;
echo $result;
}
else
{
echo "<font color='red'>Wrong Input or Method</font>";
}
?>
Next

Sunday, June 10, 2012

Calculate Age from Birth Day php


Using php You could do lot of calculations.From this tutorial i am going to introduce you popular and an interesting type of calculations.Some of calculations, I have introduced you in mysql php examples.Here you have to enter your birth days in this format of date "1965-06-12". The input field is bellow.


php codes to calculate age from birth day is as follows

<?php
$birthday=$_POST['birth_day'];
function birthday($birthday){
    $age = strtotime($birthday);
    if($age === false){
        return false;
    }
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age));
    $now = strtotime("now");
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
    $age = $y2 - $y1;
    if((int)($m2.$d2) < (int)($m1.$d1))
        $age -= 1;
    return $age;
}

echo birthday($birthday);
?>
<form method="post" action="<?php echo $PHP_SELF;?>">
<table>
<tr><td><input type="text" name="birth_day"></td></tr>
<tr><td><input type="submit" value="Enter"></td></tr>
 </form>
</table>

Using bellow scripts you will get year,month and dates also

<?php
$bday=$_POST['birth_day'];
function get_Age_difference($start_date,$end_date){
    list($start_year,$start_month,$start_date) = split('-', $start_date);
    list($current_year,$current_month,$current_date) = split('-', $end_date);
     $result = '';

   for($x=1 ; $x<=12 ; $x++){

        $dim[$x] = date('t',mktime(0,0,0,$x,1,date('Y')));

    }

    $m = $current_month - $start_month;
    $d = $current_date - $start_date;
    $y = $current_year - $start_year;

 if($d < 0) {

        $today_day = $current_date + $dim[$current_month];
        $today_month = $current_month - 1;
        $d = $today_day - $start_date;
        $m = $today_month - $start_month;
        if(($today_month - $start_month) < 0) {

            $today_month += 12;
            $today_year = $current_year - 1;
            $m = $today_month - $start_month;
            $y = $today_year - $start_year;

        }

    }

   if($m < 0) {

        $today_month = $current_month + 12;
        $today_year = $current_year - 1;
        $m = $today_month - $start_month;
        $y = $today_year - $start_year;

        }

  if($y < 0) {

        die("Start Date Entered is a Future date than End Date.");

    } else {

        switch($y) {

            case 0 : $result .= ''; break;
            case 1 : $result .= $y.($m == 0 && $d == 0 ? ' year old' : ' year'); break;
            default : $result .= $y.($m == 0 && $d == 0 ? ' years old' : ' years');

        }

        switch($m) {

            case 0: $result .= ''; break;
            case 1: $result .= ($y == 0 && $d == 0 ? $m.' month old' : ($y == 0 && $d != 0 ? $m.' month' : ($y != 0 && $d == 0 ? ' and '.$m.' month old' : ', '.$m.' month'))); break;
            default: $result .= ($y == 0 && $d == 0 ? $m.' months old' : ($y == 0 && $d != 0 ? $m.' months' : ($y != 0 && $d == 0 ? ' and '.$m.' months old' : ', '.$m.' months'))); break;

        }

        switch($d) {

            case 0: $result .= ($m == 0 && $y == 0 ? 'Today' : ''); break;
            case 1: $result .= ($m == 0 && $y == 0 ? $d.' day old' : ($y != 0 || $m != 0 ? ' and '.$d.' day old' : '')); break;
            default: $result .= ($m == 0 && $y == 0 ? $d.' days old' : ($y != 0 || $m != 0 ? ' and '.$d.' days old' : ''));

        }

    }

    return $result;

}

$date_difference= get_Age_difference($bday,date("Y-m-d"));
echo $date_difference;
?>
<form method="post" action="<?php echo $PHP_SELF;?>">
<table>
<tr><td><input type="text" name="birth_day"></td></tr>
<tr><td><input type="submit" value="Enter"></td></tr>
</form>
</table>
Next


Back ups in to XML File & .rar file php

Back ups in to XML File and .rar file php
You can get your "dept_division" in to XML file by using following php scripts file.XML file will be created in your root directory where you store your php file.

<?php
$host='localhost';
$user='root';
$pass='';
$name='my_database';
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);


$query = 'SHOW TABLES FROM '.$name;
$result = mysql_query($query,$link) or die('cannot show tables');
if(mysql_num_rows($result))
{
  
    $tab = "\t";
    $br = "\n";
    $xml = '<?xml version="1.0" encoding="UTF-8"?>'.$br;
    $xml.= '<database name="'.$name.'">'.$br;
  
  
    while($table = mysql_fetch_row($result))
    {
      
        $xml.= $tab.'<table name="'.$table[0].'">'.$br;
      
  
        $query3 = 'SELECT * FROM '.$table[0];
        $records = mysql_query($query3,$link) or die('cannot select from table: '.$table[0]);
      
  
        $attributes = array('name','blob','maxlength','multiple_key','not_null','numeric',
'primary_key','table','type','default','unique_key','unsigned','zerofill');
        $xml.= $tab.$tab.'<columns>'.$br;
        $x = 0;
        while($x < mysql_num_fields($records))
        {
            $meta = mysql_fetch_field($records,$x);
            $xml.= $tab.$tab.$tab.'<column ';
            foreach($attributes as $attribute)
            {
                $xml.= $attribute.'="'.$meta->$attribute.'" ';
            }
            $xml.= '/>'.$br;
            $x++;
        }
        $xml.= $tab.$tab.'</columns>'.$br;
      
        //stick the records
        $xml.= $tab.$tab.'<records>'.$br;
        while($record = mysql_fetch_assoc($records))
        {
            $xml.= $tab.$tab.$tab.'<record>'.$br;
            foreach($record as $key=>$value)
            {
                $xml.= $tab.$tab.$tab.$tab.'<'.$key.'>'.htmlspecialchars(stripslashes($value)).'</'.$key.'>'.$br;
            }
            $xml.= $tab.$tab.$tab.'</record>'.$br;
        }
        $xml.= $tab.$tab.'</records>'.$br;
        $xml.= $tab.'</table>'.$br;
    }
    $xml.= '</database>';
  
  
    $handle = fopen($name.'-backup-'.time().'.xml','w+');
    fwrite($handle,$xml);
    fclose($handle);
echo "xml file created";
}
?>

By using following scrips you can even create .rar file too.

<?php
backup_tables('localhost','root','','my_database');


/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = '')
{
  
    $link = mysql_connect($host,$user,$pass);
    mysql_select_db($name,$link);
  
    //get all of the tables
    if($tables == '')
    {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while($row = mysql_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
  
    //cycle through
    foreach($tables as $table)
    {
        $result = mysql_query('SELECT * FROM '.$table);
        $num_fields = mysql_num_fields($result);
      
        $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
      
        for ($i = 0; $i < $num_fields; $i++)
        {
            while($row = mysql_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++)
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }
  
    //save file
    $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.rar','w+');
    fwrite($handle,$return);
    fclose($handle);
echo " back up Created";
}
?>
Output file in your web root look is like bellow

Saturday, June 9, 2012

Back up into ms excel php

Back up into ms excel php


Some users need to have the mysql data in to ms excel format to manipulate data easily with their knowledge on excel.In here too,I have used same table as in previous tutorial("dept_division").
Run and see the bellow scripts.


<?php

$database="my_database";
$table="dept_division";
$uer="root";
mysql_connect("localhost",$uer,"");
mysql_select_db("my_database");

$result=mysql_query("select * from $table");

$out = '';

$fields = mysql_list_fields(my_database,$table);


$columns = mysql_num_fields($fields);


for ($i = 0; $i < $columns; $i++) {
$l=mysql_field_name($fields, $i);
$out .= '"'.$l.'",';
}
$out .="\n";


while ($l = mysql_fetch_array($result)) {
for ($i = 0; $i < $columns; $i++) {
$out .='"'.$l["$i"].'",';
}
$out .="\n";
}


$f = fopen ('export.csv','w');


fputs($f, $out);
fclose($f);

header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="export.csv"');
readfile('export.csv');
?>
Next

Back up a table php

Back up a table php

Previous tutorial we were discussed how to take back ups in a data base for this tutorial I have selected the table "dept_division" in my_database". Same file with following changes you can get back up of the table.

<?php

backup_tables('localhost','root','','my_database','dept_division');
$host='localhost';
$user='root';
$pass='';
$name='my_database';
$table='dept_division';


function backup_tables($host,$user,$pass,$name,$tables = '')
{
  
    $link = mysql_connect($host,$user,$pass);
    mysql_select_db($name,$link);
  
  
    if($tables == '')
    {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while($row = mysql_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
  
    //cycle through
    foreach($tables as $table)
    {
        $result = mysql_query('SELECT * FROM '.$table);
        $num_fields = mysql_num_fields($result);
       
        $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
       
        for ($i = 0; $i < $num_fields; $i++)
        {
            while($row = mysql_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++)
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }
  
    //save file
    $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
echo " back up Created";
}
?>
Next

database back up php

Database back up php

Regular back up keeping of database is very important due to system crashes.This tutorial discuss with you how to take back ups in various format of files.
First we take the back up of your "my_database" into .sql file.
create bellow php file and run it you will get a  text containing your data base as a whole.

<?php
backup_tables('localhost','root','','my_database');



function backup_tables($host,$user,$pass,$name,$tables = '')
{
  
    $link = mysql_connect($host,$user,$pass);
    mysql_select_db($name,$link);
  

    if($tables == '')
    {
        $tables = array();
        $result = mysql_query('SHOW TABLES');
        while($row = mysql_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
  
    //cycle through
    foreach($tables as $table)
    {
        $result = mysql_query('SELECT * FROM '.$table);
        $num_fields = mysql_num_fields($result);
      
        $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
        $return.= "\n\n".$row2[1].";\n\n";
      
        for ($i = 0; $i < $num_fields; $i++)
        {
            while($row = mysql_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++)
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }
  
    //save file
    $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
echo " back up Created";
}
?>

You will get .sql file in your web root where above file is created.

Next

Practical Use of Left Join php mysql

Practical Use of Left Join php mysql

Some companies will be given trainings to their staff members.In this case they maintain data base with 2 tables one with staff members details and other with trainings details.when all staff members are not trained higher executives need to know the staff members who have not trained yet.Here with this problem left joining of 2 tables in following manner executives could be easily found the staff members have not trained yet.
I have used bellow 2 tables for this purpose.

CREATE TABLE IF NOT EXISTS `dept_division` (
  `id` int(24) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  `age` varchar(46) NOT NULL,
  `division` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `training` (
  `id` int(40) NOT NULL AUTO_INCREMENT,
  `traning_id` int(40) NOT NULL,
  `training_obtained` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

According to these two tables you can see jennifer,sofia & wictor have not got any training. dept_division table "id" is used to identify the staff members in table training as "training_id".
Create following php file and run it and you get the expected result.

<?php
$host="localhost";
$username="root";
$password="";
$db_name="my_database";
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql ="SELECT dept_division.name, dept_division.age,dept_division.division FROM dept_division
    LEFT JOIN  training ON training.traning_id=dept_division.id WHERE training.traning_id IS NULL";
     $result=mysql_query($sql);
?>
<table  align="center"  bgcolor="#15475c">
<tr bgcolor="#ddeef5">
<td align="center" ><strong>Name</strong></td>
<td align="center" "><strong>Age</strong></td>
<td align="center" "><strong>Division</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr bgcolor="#d0e7f1">
<td><?php echo $rows['name']; ?></td>
<td><?php echo $rows['age']; ?></td>
<td><?php echo $rows['division']; ?></td>
</tr>
<?php
}
?>
</table>

Resulting table is

Name Age Division
jennifer 23 Production
sofia 25 service
wictor 45 production