Friday, September 25, 2009

Get the difference between time in Hours, Minutes, Seconds.

[php]
class timedifference
{
var $fromHours;
var $fromMinutes;
var $fromSeconds;
var $toHours;
var $toMinutes;
var $toSeconds;
var $Hrs;
var $Mnts;
var $Secs;
function HrsMinsSecs($fromTime,$toTime)
{
list($this->fromHours,$this->fromMinutes,$this->fromSeconds ) = explode(":",$fromTime) ;
list($this->toHours,$this->toMinutes,$this->toSeconds ) = explode(":",$toTime) ;
if($this->toHours < $this->fromHours)
return "Invalid from and to times";
$this->findSeconds();
$this->findMinutes();
$this->findHours();
return "Hours : ".$this->Hrs." Minutes : ".$this->Mnts." Seconds : ".$this->Secs;

}
function findSeconds()
{
if($this->toSeconds < $this->fromSeconds)

{
$this->Secs = ($this->toSeconds + 60) - $this->fromSeconds;
$this->toMinutes--;

}
else

{
$this->Secs = $this->toSeconds - $this->fromSeconds;
}
}
function findMinutes()
{
if($this->toMinutes < $this->fromMinutes)

{
$this->Mnts = ($this->toMinutes + 60) - $this->fromMinutes;
$this->toHours--;
}
else
{
$this->Mnts = $this->toMinutes - $this->fromMinutes;
}
}
function findHours()

{
$this->Hrs = $this->toHours - $this->fromHours;
}

} // end of class
$timeData = new timedifference();

echo $timeData->HrsMinsSecs("08:33:13","18:01:59");
[/]

Tuesday, August 25, 2009

How to expire PHP script after certain date.

"One idea can change your life." No.. No.. I am not advertiseing for Idea... I remember this word because one of my colleague was tired of some unusual work and I suggested him a shortcut, which he used and get relaxed of the said work. There is a short story behind it.

"He has designed many online submission form for our institute. However it was always required that the online submission should be closed after certain date and time. This dates always came on Saturdays/Sundays :). Oops it is so boring to come on Saturday/Sunday in office and remove link for online submission so that no one can submit their application after the expired time period. He was doing same work since last 1 year. One day I came to know this and I suggest him to put following PHP code at begining in his online submission application form and relax. Here is the code.
< ? php
$exipredate = "2009-08-31 17:00:00";
if(date('Y-m-d H:i:s')>=$exipredate)
{
echo 'Date & Time for submitting application on-line is over.';
exit;
}
?>

He implemented this and He relaxed. A small script worked better for him. Isn't it "A small idea can change your life".

I am writing this article after a long time. The delay was due to some heavy work in office. Sorry for this delay.

Wednesday, February 18, 2009

How to check user has disabled Javascript ?

This is a samble example to check the Javascript is disabled or not

< html>
< head>
< title>Testing< /title>
< /head>
< script language='javascript'>
function testJava()
{
alert("Hello good idea to enable scripting");
}
< /script>
< noscript>
< ?php
echo "PLEASE ENABLE JAVASCRIPT BEFORE PROCEEDING.";
?>
< /noscript>
< body onLoad='testJava();'>
< /body>
< ?php
echo "Yahoo... Javascript is enabled";
?>
< /html>

Thursday, February 5, 2009

Ajax !!! Why dont we try it ?

Ajax !!! is it too difficult ?

I remember the day in 1997, when I first created my mail id on yahoo. It took half an hour for me to create my first yahoo mail id. The reason was neither the speed of net connectivity nor about the typing. The delay was only due to selecting the mail id. Whatever the mail id I selected it was already occupied. My page was nearly 10 times refreshed showing me error to choose another mail id. I got bored and felt that how difficult it was to open an email account.

Now a day the scenario has been changed. You try to open an email account on any website it will take hardly five minutes. As soon as you will type your email id, immediately a box will appear showing you that the Email id, you choose, is available or not. The page does not get refreshed for this small peace of information. But the hidden activity behind this process is AJAX. The webpage will query its database and will show you the availability of email id.

Unknown things are always like a question mark! But following the question mark will lead you to its full stop. AJAX is handy useful tool to make the webpage faster and convenient.

I would like to show a simple example of AJAX. You will realize that it is not too difficult. Just go ahead and experience it.

First go to your mysql database and create a simple table.

Create table employee
(empcode int,
Empname varchar(20)
)

Now insert few data in this table.

Insert into employee values (1,”Virendra”);
Insert into employee values(2,”Sachin”);
Insert into employee values (3,”Yuvaraj”);
Insert into employee values(4,”Dhoni”);

Now we are going to create an HTML file. You can use any of your favorite editor (I use notepad++). Type the following code.

< html>
< head>
< title> Simple Ajax Application< /title>
< /head>
< script language="javascript">
// The following function is used for AJAX.
var req;
function getAjaxData()
{

req=false;

if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
var url = 'ajax_file.php';
str=empcode.value;
url =url+"?empcode="+str;
url=url+"&ms="+new Date().getTime(); // This is to send the unique ajax call.

req.onreadystatechange = processRequest;
req.open("get", url, true);
req.send(null)
}

function processRequest()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
mytext=req.responseText;
empname.innerHTML = mytext;
}
}
}
< /script>
< body>
< table border=1>
< tr> < td> Employee code< /td> < td> < input type=text name=empcode value="" onBlur="javascript:getAjaxData();"> < /td> < /tr>
< tr> < td> Employee Name< /td> < td> < div id=empname name=empname> < /div> < /td> < /tr>
< /table>
< /body>
< /html>

Now time to save the file say ajax_sample.html.

Just look into the getAjaxData() function which will be called on onBlur event of empcode. You can see, I have created an url in this function. This url will be called after you loose the focus from empcode by entering some value. Now we are going to create ajax_file.php file which is in the URL. Here is the code of ajax_file.php

< ?php
$username='root';
$password='';
$host='localhost';
$db_name="test";
$conn1=mysql_connect($host,$username,$password) or die("Unable to connect to mysql server");
$select1=mysql_select_db("$db_name",$conn1) or die("Unable to connect to mysql database");
setcookie('db_name',$db_name);

$empcode = $_GET['empcode'];
$query = "select empname from employee where empcode=$empcode";

$result = mysql_query($query);
echo mysql_result($result,0,'empname');
?>

Finished. Save the file.

What does the ajax_file.php file do ? When you move out of the empcode text box, this file will be called. It will received empode as GET method and fetch the corresponding record from the database. The value of empname will be sent back to our ajax_sample.html file. This empname will be displayed through < div> tag.


Thursday, January 22, 2009

Userwise Menu Design from mysql Database.

I was designing a database driven application. I thought to manage following utilities through the application.

1. User Creation.
2. Menu Design from database.
3. Giving rights to access the menu from the database.

To accomplish this, I have to design first the database tables. Here is an brief idea how I come near to my requirements.

1) Table design for User Creation.

CREATE TABLE `users`
(
`userid` smallint(3) unsigned NOT NULL auto_increment, // The Unique Identity for each user.
`username` varchar(30) NOT NULL // User Name
`userpass` varchar(32) NOT NULL, // Password for the user. MD5 is algorithm can be used.
`division` varchar(30) default NULL, // Division of user to which he/she belongs.
`name` varchar(50) default NULL, // Name of the User.
`label_to_print` varchar(500) default NULL, // Required if you want print any data for report printing.
`valid_from` date default NULL, // User can login from this Valid_from Date
`valid_to` date default NULL, // User can login from this Valid_to Date
`ipaddress` varchar(200) default NULL, // Required if you want to put IP restriction for any user.
`created_by` varchar(30) default NULL, // User created by the the user.
`entry_date` datetime default NULL, // Data of user creation.
`status` varchar(10) default NULL, // Status of user. User can login only if the status is Active.
PRIMARY KEY (`userid`),
UNIQUE KEY `username` (`username`)
)

2) Menu Design from Database.
I have created two tables to design the menu.
1. Table mainmenu to display root menu
2. Table submenu to leaf menu

CREATE TABLE `mainmenu` (
`mainmenuid` int(11) NOT NULL auto_increment, // Unique menu id
`mainmenuname` varchar(50) default NULL, // Main Menu name to display.
`mainmenumodule` varchar(50) default NULL, // Main menu module name to which it belongs.
`mainmenustatustext` varchar(255) default NULL, // Status message text.
`image` varchar(255) default NULL, // Image to display on menu.
`height` int(11) default NULL, // Image height
`width` int(11) default NULL, // Image width.
`userid` varchar(50) default NULL, // The record entered by the user.
`entry_date` datetime default NULL, // The record entry date.
UNIQUE KEY `mainmenuid` (`mainmenuid`)
)


CREATE TABLE `submenu` (
`mainmenuid` int(11) NOT NULL, // This column refer to mainmenu Table.
`screenid` int(11) NOT NULL, // Screen id. It should be sequential.
`print_order` smallint(6) default NULL, // Order in which to display it
`screename` varchar(50) default NULL, // Leaf menu name to display.
`screenlink` varchar(255) default NULL, // Link or filename to load the file
`image` varchar(255) default NULL, // Image file name to display
`height` int(11) default NULL, // Image height
`width` int(11) default NULL, //Image width.
`screenstatustext` varchar(255) default NULL, // Status bar message
`active` varchar(20) default NULL, // Screen is Active or Inactive.
`userid` varchar(20) default NULL, // The record entered by the user.
`entry_date` datetime default NULL, // The record entry date.
PRIMARY KEY (`mainmenuid`,`screenid`)
)
3) Table to give rights to access the menu from the database.
CREATE TABLE `user_right` (
`mainmenuid` int(11) NOT NULL, // MainMenu id
`screenid` int(11) NOT NULL, // Screen id
`username` varchar(20) NOT NULL, // Username who has access to mainmenuid+screenid
`valid_from` date default NULL, // Rights to access the screen from date.
`valid_to` date default NULL, // Rights to access the screen to date.
`userid` varchar(20) default NULL, // The record entered by the user.
`entry_date` datetime default NULL, // The record entry date.
PRIMARY KEY (`mainmenuid`,`screenid`,`username`)
)

Now create a simple view to fetch the data from the above table.
DELIMITER $$
DROP VIEW IF EXISTS `menu`$$
CREATE VIEW `menu` AS select `a`.`username` AS `username`,`c`.`mainmenuname` AS `mainmenuname`,`b`.`screename` AS `screename`,`b`.`screenlink` AS `screenlink`,`a`.`valid_from` AS `valid_from`,`a`.`valid_to` AS `valid_to` from ((`user_right` `a` join `submenu` `b`) join `mainmenu` `c`) where ((`a`.`mainmenuid` = `c`.`mainmenuid`) and (`a`.`screenid` = `b`.`screenid`) and (`a`.`mainmenuid` = `b`.`mainmenuid`)) order by `c`.`mainmenuid`,`b`.`print_order`$$
DELIMITER ;

Now insert the data in appropriate tables and you have done. Just execute the following query to access the screen rights for a single user.

Select * from menu where username="";

girishpadia@gmail.com

Monday, January 19, 2009

Enahncement to mysql_query php function.

I have extended mysql_query function to have more flexibility. It is a php file say "run_query.php". Include this file in your php application. To use this file follow these steps.
1) Create a table in mysql with the following structure.
CREATE TABLE `errorlog`
( `query` varchar(5000) default NULL,
`error` varchar(5000) default NULL )

2) Create a php file and paste following code. Save the file (say file name is run_query.php).

< ? php
function mysql_query_($query)
{ // Paste here code to connect to mysql database.
$username='root';

$password='';
$host='localhost';
$db_name="xyz";
$conn1=mysql_connect($host,$username,$password) or die("Unable to connect to mysql server");
$select1=mysql_select_db("$db_name",$conn1) or die("Unable to connect to mysql database");
$curdate = date("d-m-Y H:i:s");
if(mysql_query($query) == true) // The queri is fired and checked.
{
if(substr(strtoupper($query),0,6) == 'INSERT' substr(strtoupper($query),0,5) == 'UPDATE' substr(strtoupper($query),0,5) == 'DELETE') // The query is checked for Insert/Update/Delete
{
$fp=fopen("trans.sql","a"); //If query is type of Insert/Update/Delete then it will store the query into trans.sql file.
if($fp==null)
{
die("File cannot be opened. Try again !!!");

}
$printline = "/* $curdate : */ $query ;";
fprintf($fp,"\r\n%s",$printline);
fclose($fp);
return true;
}
else
{
return mysql_query($query);
}
}
else
{
$error = mysql_error();
$error = addslashes($error);
$query = addslashes($query);
mysql_query("insert into errorlog values('$query','$error')");
return false;
}
}
? >

3) Include this file in your any php application. (Command to include file : )
4) Use mysql_query_ function instead of mysql_query function.
e.g.
/*< ? php $query = "select * from employee";
$result = mysql_query _($query)
? >
*/
Advantages.
  1. You can log query and error in your database table (errorlog).
  2. A sql file created/appendended whenever any Data manipulation query is fired. So you can have a complete transaction log in query format.
  3. This sql "trans.sql" file will help you in "point in time recovery" in case of the database is crashed.
Your views ,comments and updation in this function are welcome.
Please mail on girishpadia@gmail.com