Thursday, 19 May 2011

PHP FUNCTIONS - WHY PHP FUNCTIONS ARE USEFUL




The PHP programming language proposes a set of predefined functions for you to accomplish the most simple tasks.

For instance, when you want to print the content of a PHP variable $var, you can use the print() function. Such a task is so elementary that not providing a specific PHP command for it would be ridiculous; conversely, it would be equally nonsensical to provide predefined PHP functions for every possible sequence of PHP commands, since such functions would hardly be used because they are based on very particular web development needs.

As a web developper, you are thus able to define your own functions in PHP, that is to say sequences of PHP statements which can accept parameters and can be called from different places of a script in order to complete a defined set of tasks whenever you need it.

The reasons you can have for defining a PHP function are severalfold:
  • There is a sequence of PHP commands that you will need to reuse multiple times in your script(s).
  • A sequence of commands that needs to be executed in your PHP script requires a common set of client-defined parameters.

PHP FUNCTIONS - HOW TO DEFINE A FUNCTION IN PHP


The PHP syntax to define a function is rather easy to remember:

function function_name($par_1, ... , $par_n)
{
php_instructions
}
  • where function_name is the name of your function (a PHP function name must have the same form as a PHP variable name, the only difference being that you must not put a dollar symbol in front of it)
  • where the $par_i denote parameters that are accepted by the function (its arguments, in other words)
  • where php_instructions is the set of PHP instructions that must be executed by the function.


Remarks:

  • Unlike PHP variable names, PHP function names are case insensitive. It is however recommended to remain rigorous when naming and calling any PHP object (remember what we said about how easy it is to make errors in loosely typed programming languages).
  • A function can be defined within another function.
  • Every function has a global scope (even if it was defined within another function).



PHP FUNCTIONS - RECURSIVE PHP FUNCTIONS



PHP allows the definition of recursive functions, that is to say functions that call themselves within their own definition in order to get evaluated by induction. An example of recursive PHP function is provided below:

Learn the PHP code:
<?php
function cumulative_sum($number)
{
$result = 0;
if ($number > 0)
$result = $number + cumulative_sum($number-1);
return ($result);
}
?>

Run the PHP script in your web browser:

Recursive functions in PHP

Remark:

The return() statement ends the execution of the function and returns the value of the function call (which is taken as an argument of return()).

PHP functions allow you to group a particular set of PHP commands which require a common set of arguments; in this way, a PHP function can be called multiple times within your script, or even be exported to other scripts by using the include() statement (or the require() statement). PHP functions constitute the building blocks of your applications.

PHP INCLUDE AND PHP REQUIRE




PHP includes allow you to import HTML/PHP code from external files to your current PHP script.

This allows you to reuse the same lines of code with only one declaration and might be very useful, for instance when you want to assign the same template to all the pages of your website without including the whole code of this template within every webpage.

Thefore, if you need to modify the template of your webpages in the future, all you will have to do is modify the original template file and all the other pages of your website will automatically be updated since they all fetch their code from this file. The PHP syntax of theinclude() statement will be introduced below.


PHP INCLUDE AND PHP REQUIRE - PHP INCLUDE



Given a file whose path is called file_path (file_path is a string giving the address of the file, for instance 'file.php' or '/folder/file.php', etc ...), the PHP syntax is given by:
include(file_path)


In the example below, a file called complements.php will be added as an include within another file called main.php (in order to simplify the path, we will put both files in the same folder).

Learn the PHP code:
complements.php
<?php
$s = 1;
?>

main.php
<?php
include('complements.php');
echo $s+1;
?>


Run the PHP script in your web browser:

php include() statement

Remark:

When executing an include() statement, the external file which has been included is processed as HTML by default, even though the include statement was inserted within a php script.
If the include file contains PHP code, you must place that code between the tags <?php and ?> within the include file itself.

PHP INCLUDE AND PHP REQUIRE - PHP REQUIRE


The only difference between the PHP include and PHP require statements is that the PHP require() statement triggers a fatal error when the file included cannot be found, while the include() statement only issues a warning.

The PHP include() and require() statements() allow you to reuse your PHP code and gain time and flexibility. Typically, they allow you to group variables or functions in one PHP file and then make them available to any other page of your website. They also allow you to optimize the development of templates for more flexibility.








///////////////////////////////formvalidation///////////////////////////////////////////


<html>
<head>
<title>JQuery Form Example</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#feedback').load('check.php').show();
$('#namein').keyup(function()
{
$('#feedback').html(" ");
$.post('check.php',{ name:myform.name.value},
function(result)
{


$('#feedback').html(result).show();




});
});


/*$('#pono').onblur(function(){


$.post('check.php',{phno:myform.pheno.value},
function(result){


$('#pono').html(result).show();
});


)};*/


$("#myform").validate({ debug: false,rules: {
name: "required",
email: {required: true,email: true},
pheno: "required",
city: "required"},
messages: {name: "Please let us know who you are.",email: "A valid email will help us get in touch with you.",pheno:"Enter correct no",city:"enter the city name"},

});



});
</script>
<style type="text/css">
label.error { width: 250px; display: inline; color: red;}
div#feedback { display:inline;}
form{position:fixed;
top:30px;
right:5px;}

</style>
</head>
<body>
<form name="myform" id="myform" action="insert.php" method="POST">  
<!-- The Name form field -->
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="namein" size="30" value=""/><div id='feedback'></div>  
<br>
<label for="password" id="pass">password</label>< 
    <input type="password" name="pass" id="password" size="30" value=""/><br>
<label for="fname" id="fname">firstname</label>  
    <input type="text" name="fname" id="finame" size="30" value=""/><br>
<label for="lname" id="lname">lastname</label>  
    <input type="text" name="lname" id="laname" size="30" value=""/><br>
<!-- The Email form field -->
    <label for="email" id="email_label">Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/> 
<br>
<!-- phno -->
<label>phno</label>
<input type="text" name="pheno" id="phno" size="30" /><br>
<label>city</label>
<input type="text" name="city" id="city" size="30" /><br>
<label for="male" id="male_id">male</label>  
    <input type="radio" name="gender" id="genderid" size="30" value="male"/>
<label for="female" id="female_id">female</label>
<input type="radio" name="gender" id="genderid" size="30" value="Female"/><br>
<!-- The Submit button -->
<input type="submit" name="submit" value="Submit"> 
</form>


</body>
</html>










/////////////////////////////////////style forms/////////////////////////////////////////////////////



<html>
<head>
<title>JQuery Form Example</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#feedback').load('check.php').show();
$('#namein').keyup(function()
{
$('#feedback').html(" ");
$.post('check.php',{ name:myform.name.value},
function(result)
{


$('#feedback').html(result).show();




});
});


/*$('#pono').onblur(function(){


$.post('check.php',{phno:myform.pheno.value},
function(result){


$('#pono').html(result).show();
});


)};*/


$("#myform").validate({ debug: false,rules: {
name: "required",
email: {required: true,email: true},
pheno: "required",
city: "required"},
messages: {name: "Please let us know who you are.",email: "A valid email will help us get in touch with you.",pheno:"Enter correct no",city:"enter the city name"},

});



});
</script>
<style type="text/css">
label.error { width: 250px; display: inline; color: red;}
div#feedback { display:inline;}
form{position:fixed;
top:30px;
right:5px;}

</style>
</head>
<body>
<form name="myform" id="myform" action="insert.php" method="POST">  
<!-- The Name form field -->
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="namein" size="30" value=""/><div id='feedback'></div>  
<br>
<label for="password" id="pass">password</label>< 
    <input type="password" name="pass" id="password" size="30" value=""/><br>
<label for="fname" id="fname">firstname</label>  
    <input type="text" name="fname" id="finame" size="30" value=""/><br>
<label for="lname" id="lname">lastname</label>  
    <input type="text" name="lname" id="laname" size="30" value=""/><br>
<!-- The Email form field -->
    <label for="email" id="email_label">Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/> 
<br>
<!-- phno -->
<label>phno</label>
<input type="text" name="pheno" id="phno" size="30" /><br>
<label>city</label>
<input type="text" name="city" id="city" size="30" /><br>
<label for="male" id="male_id">male</label>  
    <input type="radio" name="gender" id="genderid" size="30" value="male"/>
<label for="female" id="female_id">female</label>
<input type="radio" name="gender" id="genderid" size="30" value="Female"/><br>
<!-- The Submit button -->
<input type="submit" name="submit" value="Submit"> 
</form>


</body>
</html>






///////////////////////////////////////insert.php//////////////////////////////////////

<?php
mysql_connect("localhost","root","");
mysql_select_db("test") or die(mysql_error());
if(isset($_POST['name'],$_POST['city'],$_POST['phno'],$_POST['email']))
{
$name=$_POST['name'];
$pass=$_POST['city'];
$phno=$_POST['phno'];
$email=$_POST['email'];


/*$error=array();
if(empty($name)||empty($pass)||empty($phno)||empty($email) )
{


$error[]="u forget some filled ";


}
else
{


if(strlen($name)>20)
{  $error[]= "Name too long";  }
if(filter_var($email,FILTER_VALIDATE_EMAIL)===FALSE)
{


$error[]="plz give the valid email";


}
if(!is_numeric($phno))
{  $error[]="plz enter the phone no";}
}
if(!empty($error))
{


foreach($error as $errors)
{


echo "<b>".$errors;


}


}*/




$ins=mysql_query("insert into tab1(name,city,phno,email) values ('$name','$city','$phno','$email')");
if($ins)
{
echo "sucessfully inserted";
}
else
{
echo "it will not insert";
}


}


?>




//////////////////////////////////////////////////pagination////////////////////////////////////////////



<html>
<head>
</head>
<body>
<table border="10">
<tr><th>name</th><th>Email</th><th>phno</th><th>city</th></tr></table>
</body>
</html>
<?php
//mysql start position
$start=0;
//record per page
$pp=2;




//current page
if(!isset($_GET['page']))
{
$page=1;
}
else
{
$page=$_GET['page'];
}




//mysql start position




if($page<=1)
$start=0;
else
$start=$page * $pp - $pp;








//connect  db
$con=mysql_connect("localhost","","");
mysql_select_db("test",$con) or die("no msg");
$r="select * from tab1";
$dis="select * from tab1 LIMIT $start,$pp";
//how much records in db
$no_row=mysql_num_rows(mysql_query($r));
$no_pag=ceil($no_row/$pp);
//append 
//$dis.="LIMIT $start,$pp";
$res=mysql_query($dis);


while($row=mysql_fetch_array($res))
{


echo $row['name']."&nbsp".$row['phno']."<br>";
}
//prev




$prev=$page-1;








//next
$next=$page+1;
//prev
if($prev > 0)
echo "<a href='?page=$prev'>prev</a>";








$number=1;
for($number;$number<=$no_pag;$number++)
{
echo "<a href='?page=$number'>$number</a> ";
}




if($page<ceil($no_row/$pp))
echo "<a href='?page=$next'>next</a>";




?>





//////////////////////////////////////////loginin.php/////////////////////////////////////////




<?php
include 'oop.php';
if(logi())
{


header("Location:output.php");
}


if(isset($_POST['login']))
{


$name=$_POST['name'];
$pass=$_POST['pass'];
if(isset($_POST['rembr']))
$rembr=$_POST['rembr'];
else
echo "";


if($name&&$pass)
{


$login=mysql_query("select * from log where name='$name'");
while($row=mysql_fetch_assoc($login))
{
$dbp=$row['id'];


if($pass==$dbp)
$loginok=TRUE;
else
$loginok=FALSE;




if($loginok==TRUE)
{


if($rembr=="on")
setcookie("name",$name,time()+7200);


else if($rembr=="")
$_SESSION['uname']=$name;


header("Location:output.php");
exit();
}
else
{die("incorre password ");}


}


}
else
die("incorrect user name/password");


 }




?>
<form action="in.php" method="POST">
name<input type="text" name="name" /><br>
pass<input type="password" name="pass" /><br>
<input type="checkbox" name="rembr" /><br>
<input type="submit" name="login" value="submit"/><br>
</form>




///////////////////////////////oop.php///////////////////////////////////////////////////




<?php
session_start();
mysql_connect("localhost","","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());




//login check function
function logi()
{


if(isset($_SESSION['uname'])||isset($_COOKIE['name']))
{


$logi=TRUE;
return $logi;


}
}
/*class dis
{
var $name=10;
function get()
{


echo $this->name;
}
function ri()
{
echo $this->get();
}
}


$get=new di";
echo $get->get()."<br>";
echo $get->ri();
echo $get->name;*/

?> 

Saturday, 14 May 2011

PHP STRINGS - SINGLE QUOTED PHP STRINGS





The simplest form of PHP strings is the single quoted PHP string; it consists in putting the chain of characters constituting your string between single quotes (for instance, consider the PHP string $s = 'understanding').


The particularities of single quoted PHP strings are the following:
  • if you intend to have a literal single quote in your chain of characters, you need to escape it with a backlash \ in order to prevent it from being mistaken with the single quote which terminates the string.

    Learn the PHP code:
    <?php
    $s = 'Here\'s how you do it';
    echo $s;
    ?>

    Run the PHP script in your web browser:

    Escaping single quotes in php strings
  • likewise, if you intend to have a backlash followed by a single quote within your chain of characters, you need to double the backlash, etc ...

    Learn the PHP code:
    <?php
    $s = 'String terminating with (one) backlash \\';
    echo $s;
    ?>


    Run the PHP script in your web browser:

    Double backlash in PHP strings
  • if you intend to terminate your chain of characters with a backlash, you need to double it.
  • PHP variables within single quoted strings are not parsed.

    Learn the PHP code:
    <?php
    $var = 1;
    $s = 'The variable $var will not be parsed';
    echo $s;
    ?>


    Run the PHP script in your web browser:

    PHP variable not parsed in single quoted string

    PHP STRINGS - DOUBLE QUOTED PHP STRINGS

    The essential difference between a single quoted PHP string and a double quoted PHP string lies in the fact that a PHP variable will be parsed in the latter and won't be parsed in the former.
    Learn the PHP code:
    <?php
    $var = 1;
    $s = "The variable $var will now be parsed";
    echo $s;
    ?>
    Run the PHP script in your web browser:
    php variable parsed in double quoted string

Friday, 13 May 2011

PHP ARRAY AND ARRAY OF ARRAYS - PHP ARRAY




Using the PHP function array() in order to create an array

  • An array is a table of values which have been assigned to certain keys (a key is also called an "index").
  • A key can be an integer or a string.
  • The syntax to follow with the function array() is:
    array(key1 => value1,...,keyn => valuen)
Learn the PHP code:

<?php
$my_array = array(1, TRUE, 3 => 'john', 5);
print_r($my_array);
?>

Remark:

The function print_r() displays the array in a human-readable format (print_r stands for "print readable").

Run the PHP script in your web browser:

Creating arrays in PHP

Explanation:
  • By default, in the absence of a key, the array function will choose the rank of the value in the array() declaration: for instance, TRUE is the second value declared, therefore it will automatically be assigned to the key 1 (remember that the first key is 0, and not 1).
  • The value 'john' is assigned to the key 3. Afterwards, by default, in absence of explicit keys, the key 4 will be automatically chosen (because the last key assigned was key 3); the key 2 will therefore be left unassigned, unless you explicitly do it.
  • When a value is explicitly assigned to a negative integer key (which is allowed), the next key to be assigned by default (if no explicit key is given) is the key 0.

    Learn the PHP code:

    <?php
    $a = array(-5 => 3, 2, -4 => 4);
    print_r($a);
    ?>


    Run the PHP script in your web browser:

    Negative keys in PHP arrays
  • If two different values have been assigned to the same key, the last value assigned will prevail.
  • It is possible to use string keys at the same time as integer keys:


    Learn the PHP code:

    <?php
    $my_array = array(1, TRUE, 3 => 'john', 'other' => 8, 5);
    print_r($my_array);
    ?>

    Run the PHP script in the web browser:

    String keys for PHP arrays

    Remark:

    Just like before, the 5th value assigned (which happens to be a 5) will be automatically assigned to the key 4 (since the last integer key to be assigned was 3).
Using the square brackets syntax in order to create or modify an array

The value of an array A associated with a given key n (respectively with a string key 'key') is designated by $A[n] (respectively by $A['key']).
Reciprocally, you can very well define your array by assigning values to keys on a case by case basis:

Learn the PHP code:

<?php
$my_array = array(1, TRUE, 3 => 'john', 'other' => 8, 5);
echo $my_array[3].'<br>';
$my_array['other']='new';
print_r($my_array);
?>

Run the PHP script in your web browser:

Creating arrays in PHP

PHP ARRAY AND ARRAY OF ARRAYS - PHP ARRAY OF ARRAYS


We have seen that an array is a map assigning values to keys. There is no restriction on the type of values: in particular, such values can be arrays themselves. In this case, we will say that we have an array of arrays, which roughly corresponds to a multidimensional table (matrix). The example below gives the example of a 2-dimensional PHP array which replicates the 3 x 3 multiplication table:

Learn the PHP code:

<?php
$my_array = array(1 => array(1 => 1, 2 => 2, 3 => 3), 2 => array(1 => 2, 2 => 4, 3 => 6), 3 => array(1 => 3, 2 => 6, 3 => 9));
echo '2 x 3 = '.$my_array[2][3];
?>

Run the PHP script in your web browser:

Array of arrays in PHP

Remark:

By the same token, you can define an array of array of arrays, etc ... by induction.

PHP ARRAY AND ARRAY OF ARRAYS - PHP ARRAY FUNCTIONS


There exist a lot of array functions; we will introduce here a couple of them. The interested reader will be able to find the exhaustive list of PHP array functions in the PHP manual.

The sizeof function

sizeof($array) returns the number of elements contained in $array.


The implode function

The implode() function is a very useful one; it allows you to return the values of an array as a string, each of the values being separated by a string called the glue parameter (which can be a comma, for instance).
The syntax is given by implode($array,glue_parameter).


Learn the PHP code:

<?php
$array2 = array(1 => 'one', 2 => 'two');
$result = implode($array2,' , ');
echo $result;
?>

Run the PHP script in your web browser:

PHP implode function


The explode function

The explode() function is the reciprocal function of implode(): given a string $string and a delimiter $delimiter (which is a string acting as a separator, for instance a comma), explode($string,$delimiter) will return an array composed of the substrings of $string which are delimited by the separator $delimiter.
Let's now try to reconstruct the array from the example above by using the explode() function.


Learn the PHP code:

<?php
$delimiter = ' , ';
$string = 'one , two';
$result = explode($delimiter, $string);
echo $result; ?>


Run the PHP script in your web browser:

PHP array explode function

PHP ARRAY AND ARRAY OF ARRAYS - PHP ARRAY OPERATORS


You can use for arrays most of the operators that were defined in the previous tutorial (==, ===, !=, !==); you can also use the operator + which denotes the union of two arrays: $array1 + $array2 will transfer all the values of $array2 into $array1 (if two values are assigned to the same key, the value from $array1 will be preserved).

Learn the PHP code:
<?php
$array1 = array(1 => 'one');
$array2 = array(1 => 'other', 2 => 'two');
$array = $array1 + $array2;
print_r($array);
?>


Run the PHP script in your web browser:
Union of two arrays in PHP

Remark:
If instead of printing $array1 + $array2 you decide to print $array2 + $array1, the value assigned to key 1 will be 'other' instead of 'one'.
PHP arrays are a useful way to handle series of variables; they come with a lot of php array functions and operators which make such series very convenient to manipulate.

Thursday, 12 May 2011

PHP OPERATORS - PHP ARITHMETIC OPERATORS





Given two variables $var1 and $var2 in your script, you can use:
  • the addition operator:
    $var1+$var2
  • the subtraction operator:
    $var1-$var2
  • the multiplication operator:
    $var1*$var2
  • the division operator:
    $var1/$var2
  • the negation operator:
    -$var1

PHP OPERATORS - PHP COMPARISON OPERATORS


We can distinguish the following PHP comparison operators:
  • the equal sign ==:
    this is the sign we were talking about in the previous section. This PHP comparison operator tests for equality in a "loose way", meaning that the two expressions tested need not be of the same type: for instance, testing 2 == '2' will return TRUE, while in fact 2 is an integer whereas '2' is a string. Indeed, when you compare an integer with a numerical string, the numerical string will first be converted into an integer; similarly, if you compare two numerical strings, they will first be converted into integers.
    In order to remedy this limitation, another symbol (the identical sign) was introduced.
  • the identical sign ===:
    the identical sign checks for rigorous equality (i.e. equality + equality of types).
  • the not equal sign !=:
    the not equal sign checks for absence of equality (in the sense ==).
  • the not identical sign !==: the not identical sign returns TRUE if the two elements being tested are not identical (in the sense ===).
  • the less than sign <:
    $a < $b returns TRUE if $a is strictly less than $b.
  • the sign greater than >:
    $a > $b returns TRUE if $a is strictly greater than $b.
  • the sign less than or equal to <=:
    $a <= $b returns TRUE if $a is strictly less than or equal to $b.
  • the sign greater than or equal to >=:
    $a >= $b returns TRUE if $a is strictly greater than or equal to $b.

PHP OPERATORS - PHP LOGICAL OPERATORS


The logical operators in PHP are:
  • the and operator:
    $a$ and $b$ returns TRUE when both $a$ and $b$ are TRUE
    $a$ and $b$ can also be written $a && $b; the two expressions are almost equivalent, the only difference being that && has a higher precedence than most usual assignment and comparison operators; for instance, have a look at the PHP code below:


    Learn the PHP code:
    <?php

    $a = true && false;

    if ($a == false)
    echo '$a is FALSE';
    else
    echo '$a is TRUE';

    ?>

    Run the PHP script in your web browser:
    php and operator

    Remark:
    In the above PHP code, the expression $a = true && false is equivalent to the expression $a = (true && false) because the operator && has higher precedence than the operator =. Thus in this case the variable $a will be FALSE.
    This is not the case for the operator and, so that the expression $a = true and false will be interpreted as ($a = true) and false. Thus in this case the variable $a will be TRUE. You can verify this by executing the modified PHP code.
  • the or operator:
    $a$ or $b$ returns TRUE when either $a$ or $b$ is TRUE
    $a$ or $b$ can also be written $a || $b; here again, the two expressions are rouhgly equivalent, the only difference being that && has a higher precedence.
  • the xor operator:
    $a$ xor $b$ returns TRUE when either $a$ or $b$ is TRUE, but not both.
  • the not operator, written !:
    !$a returns TRUE when $a is FALSE (i.e. when $a is not TRUE).
PHP operators are very much like those you have probably already met in other programming languages; the only point that demands special attention is that the equal operator in PHP is written == and not = (which is the PHP assignment operator).












                    I.    MySQL use case


Consider the following MySQL tables :


CREATE TABLE `clients` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL
) ENGINE = MYISAM


CREATE TABLE `calls` (
  `client_from` int(10) unsigned NOT NULL,
  `client_to` int(10) unsigned NOT NULL,
  `duration` int(10) unsigned NOT NULL,
  `cost` decimal(6,1) unsigned NOT NULL,
  `date` timestamp NOT NULL default '0000-00-00 00:00:00'
) ENGINE=MyISAM DEFAULT CHARSET=latin1



The « clients » table stores the different clients of a company providing mobile phone services.
Each client has a unique identifier (the « id » field) and other information (only a name to keep it simple).

The « calls » table stores each call between clients of the company. The « client_from » is the id of the calling client and client_to is the id of the callee. These ids exist in the clients table. Duration is stored in seconds and cost in ruppees. The data field store the starting date of the call.

  • All the SQL statements must be written as single query and for a MySQL 5 database.
  • Answers are not unique. There exist several manners to get same results. Please give the most optimized choice and/or the most simple way if you can. Please privilegiate solutions using EXPLICIT JOIN synthax (INNER JOIN, LEFT JOIN …)
  • If you don’t know how to answer or have any doubts, please answer by explaining your misunderstanding or issues faced.


Please answer the following questions:

  1. Write a SQL statement to only get the « name » of all the company’s client.
Answer: SELECT `name` FROM `clients` ;
  1. Write a SQL statement adding the « Mittal » client to the « clients »’s table
Answer: INSERT INTO `clients`(`name`) VALUES('Mittal');
  1. Write a SQL statement to get the name and id of the clients who called at least one time. There must be unique results. Please give two possible answers if possible.
Answer :
1.      SELECT a.`name`, a.`id` from `clients` a JOIN `calls` b on a.`id` = b.`client_from` group by a.`id`;
2.      SELECT `name`, `id` from `clients` WHERE `id` IN (SELECT `client_from` FROM `calls` GROUP BY `client_from`);
  1. Write a SQL statement to get the name and id of the clients who received at least one call. There must be unique results. Please give two possible answers if possible.
Answer :
1.      SELECT a.`name`, a.`id` from `clients` a JOIN `calls` b on a.`id` = b.`client_to` group by a.`id`;
2.      SELECT `name`, `id` from `clients` WHERE `id` IN (SELECT `client_to` FROM `calls` GROUP BY `client_to`);
  1. Write a SQL statement to get the name and id of the clients who have no received a called yet. There must be unique results.
Answer : SELECT a.`name`, a.`id` from `clients` a LEFT JOIN `calls` b on a.`id` = b.`client_to` AND b.`client_to` IS NULL;
  1. Write a SQL statement to get the name and id of the clients who have not called someone yet. There must be unique results.
Answer : SELECT a.`name`, a.`id` from `clients` a LEFT JOIN `calls` b on a.`id` = b.`client_from` AND b.`client_from` IS NULL;
  1. Write the most simple SQL statement to get all the calls starting from the 24/01/2009 and the 03/03/2009 (start date and end date included).
Answer: SELECT `client_from`, `client_to`, `duration`, `cost`, `date` FROM `calls` WHERE `date` BETWEEN '2009-01-24' AND '2009-03-03';
  1. Write a SQL statement to get the total cost of all calls made by the client « JOHN » with the id 42. Only this total cost must be returned and it must be named as « total_cost »
Answer: SELECT SUM(`cost`) AS total_cost FROM `calls` WHERE `client_from` = '42';
  1. Write a SQL statement to get the total cost associated to each caller.
Answer: SELECT SUM(`cost`) AS total_cost FROM `calls` GROUP BY `client_from`;
  1. Write a SQL statement to insert a new call in the « calls » table. This call was made by the client id 42 to the client id 56 and lasted 40 minutes. The communication cost is 1 ruppee/minute. The call began at 10pm on the 21/05/2009.
Answer: INSERT INTO `calls`(`client_from`, `client_to`, `duration`, `cost`, `date`) VALUES('42', '56', '40', '40', '2009-05-21 22:00:00');
  1. What is not optimized in the structure of the « calls » table regarding the previous statments you wrote (Q. 3, 4, 5, 6) ? Are there something else not optimized for this table ?
Answer : Not setup foreign key in calls table `client_from` and `client_to` to `clients` table `id` column. Because the `calls` table `clients_from` and `clients_to` based on the clients table.

                   II.    PHP, HTML and JavaScript use case


  1. Write a PHP code displaying the current date. The script must ouput the date in the following format: 15/08/2009 02:55
Answer:
 <?php
                        echo date("d/m/Y H:i");
            ?>
  1. Write a simple (no formatting, no design) HTML  « login » form displaying an email texbox, a password textbox and a submit button. This form must send the data to the current PHP file using the appropriate HTTP method. You are required to write the structure of the HTML document displaying the form (just the needed markup to work, no design or xHTML validation!)
Answer:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form</title>
</head>
<body>
<div id="login_box">
  <form name="form_login" id="form_login" action="login.php" method="post">
    <fieldset>
      <legend>Login</legend>
      <table border="0" cellspacing="0" cellpadding="0" style="width:400px;">
        <tr>
          <td>Email: <em class="star">*</em></td>
          <td><input type="text" name="email" id="email" value="" /></td>
        </tr>
        <tr>
          <td>Password: <em class="star">*</em></td>
          <td><input type="password" name="password" id="password" value="" /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input type="submit" name="login" id="login" value="Login" />
            <input type="reset" name="reset" id="reset" value="Reset" /></td>
        </tr>
      </table>
    </fieldset>
  </form>
</div>
</body>
</html>
  1. Add to the previous form a Javascript Validation check (email should contain an @ and a dot). Password must not be empty. In case of errors, do not use the alert() function but display an error message above the form using JavaScript.
Answer:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form</title>
<script type="text/javascript" language="javascript">
function $m(id) {
            return document.getElementById(id);// return html element object
}

function validate_login() {    
           
            var error = "";
            var email = $m('email').value;
            var password = $m('password').value;
           
            //          reset the error mesasge
            $m('mosmsg').innerHTML = '';
           
            //          check email address is empty
            if(email == "") {
                        error += "<li>Enter email address<li>";
            }
            else {
                        if(email.indexOf("@") == -1 || email.indexOf(".") == -1) {
                                    error += "<li>Enter valid email address<li>";            
                        }
            }
           
            if(password == "") {
                        error += "<li>Enter password<li>";   
            }
           
            //          check the error occured occured or not
            if(error != "") {
                       
                        $m('mosmsg').innerHTML = error;
                        return false;
            }
           
            return true;
}
</script>
</head>
<body>
<div id="mosmsg">&nbsp;</div>
<div id="login_box">
  <form name="form_login" id="form_login" action="login.php" method="post">
    <fieldset>
      <legend>Login</legend>
      <table border="0" cellspacing="0" cellpadding="0" style="width:400px;">
        <tr>
          <td>Email: <em class="star">*</em></td>
          <td><input type="text" name="email" id="email" value="" /></td>
        </tr>
        <tr>
          <td>Password: <em class="star">*</em></td>
          <td><input type="password" name="password" id="password" value="" /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input type="submit" name="login" id="login" value="Login" onclick="return validate_login();" />
            <input type="reset" name="reset" id="reset" value="Reset" /></td>
        </tr>
      </table>
    </fieldset>
  </form>
</div>
</body>
</html>


another way of calling javascript validate_login() function is

<form name="form_login" id="form_login" action="login.php" method="post" onsubmit="return validate_login();">
  1. Javascript can be disabled on the browser. So add to the previous form a PHP validation once the user submits the form. This validation is the same than the JavaScript one. In case of error, display an error message above the HTML form.
Answer:
<?php
            //          declare variable for error message
            $error = "";
           
            /**
            *
            *          function return user input value
            *         
            *          @params name of the html elements
            *
            *          @return string value if value exists otherwise return NULL
            */
            function param_post($name, $default = false) {
                       
                        //          Check the name exist and it contains non empty value
                        if(isset($_POST[$name]) && trim($_POST[$name]) != "") return trim($_POST[$name]);
                       
                        return NULL;// return null value if element not exist or it contains empty value
            }
           
            //          check the user click the login button or not
            if(param_post('login') == 'Login') {
                       
                        //          assign values to variables
                        $email = param_post('email');
                        $password = param_post('password');
                       
                        //          Validate inputs from user
                        // check email field empty
                        if($email == "") $error .= '<li>Enter email address<li>';
                        //          check the email contain @ and . charector
                        if(strstr($email, '@') === FALSE || strstr($email, '.') === FALSE) $error .= '<li>Enter valid email address<li>';
                        //          check password is empty
                        if($password == "") $error .= '<li>Enter password<li>';
                       
                        //          check the error mesasge is exist
                        if(!$error) {
                                   
                                    //          here check login information or valid or not using database and select queries
                                    //          if valid redirected to user home page using header function
                        }
            }//        endif, check login button
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Form</title>
<script type="text/javascript" language="javascript">
function $m(id) {
            return document.getElementById(id);// return html element object
}

function validate_login() {    
           
            var error = "";
            var email = $m('email').value;
            var password = $m('password').value;
           
            //          reset the error mesasge
            $m('mosmsg').innerHTML = '';
           
            //          check email address is empty
            if(email == "") {
                        error += "<li>Enter email address<li>";
            }
            else {
                        //          check the
                        if(email.indexOf("@") == -1 || email.indexOf(".") == -1) {
                                    error += "<li>Enter valid email address<li>";            
                        }
            }
           
            if(password == "") {
                        error += "<li>Enter password<li>";   
            }
           
            //          check the error occured occured or not
            if(error != "") {
                       
                        $m('mosmsg').innerHTML = "<ul>" + error + "</ul>";
                        return false;
            }
           
            return true;
}
</script>
</head>
<body>
<?php echo $error?'<div id="mosmsg">'. $error .'</div>':'';?>
<div id="login_box">
  <form name="form_login" id="form_login" action="login.php" method="post">
    <fieldset>
      <legend>Login</legend>
      <table border="0" cellspacing="0" cellpadding="0" style="width:400px;">
        <tr>
          <td>Email: <em class="star">*</em></td>
          <td><input type="text" name="email" id="email" value="" /></td>
        </tr>
        <tr>
          <td>Password: <em class="star">*</em></td>
          <td><input type="password" name="password" id="password" value="" /></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input type="submit" name="login" id="login" value="Login" onclick="return validate_login();" />
            <input type="reset" name="reset" id="reset" value="Reset" /></td>
        </tr>
      </table>
    </fieldset>
  </form>
</div>
</body>
</html>
another way of calling javascript validate_login() function is
<form name="form_login" id="form_login" action="login.php" method="post" onsubmit="return validate_login();">