31 October, 2010

Get all month names between two dates in php

Yesterday i faced a problem regarding date manipulation in php. I had to get all month names between two dates, after some work around, i managed to make it work. I created a function "get_months" and passed two dates i.e. start date and end date to find list of months between the two dates.
Here's the function:

function get_months($date1, $date2) {
//convert dates to UNIX timestamp
$time1 = strtotime($date1);
$time2 = strtotime($date2);
$tmp = date('mY', $time2);

$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));

while($time1 < $time2) {
$time1 = strtotime(date('Y-m-d', $time1).' +1 month');
if(date('mY', $time1) != $tmp && ($time1 < $time2)) {
$months[] = array("month" => date('F', $time1), "year" => date('Y', $time1));
}
}
$months[] = array("month" => date('F', $time2), "year" => date('Y', $time2));
return $months; //returns array of month names with year
}

Thats it. I hope this helps someone like me.

20 October, 2010

Compare dates using PHP

Some times before, one of my friend asked me how to compare two dates using php. As he was a beginner and didnt have much knowledge regarding date and time functions in php, i did some kind of explanation to him.
We can use a php function strtotime in order to compare two dates in php. strtotime converts any date format description to Unix timestamp, and what we can do is convert, dates that are to be compared, to unix timestamp and perform a simple comparision.
Let's assume, we need to check if our registration has expired.

//first take today's date
$todaysDate = date("Y-m-d");

//get the expiration date, mat be from database or somewhere else
$expirationDate = "2010-12-06";

//now we convert both, today's date and expiration date to unix timestamp
$todaysDateStr = strtotime($todaysDate);
$expirationDateStr = strtotime($expirationDate);

//now simply compare the two variables
if($expirationDateStr > $todaysDateStr) {
echo "Your registration is valid!";
}
else {
echo "Your registration has expired!";
}

And that's it. The date format can be any like "-" or "/". Just convert it to unix timestamp and then compare the dates using php comparision operators.
I hope this helps someone.

12 October, 2010

How to check for numeric value using Javascript

We can use some simple function to check numeric value using javascript. The following is code snippet that checks if a value is numeric or not, returns false if not numeric else returns true.
Hope this helps someone.

//following function is used to check for a numeric value
function is_numeric(numVal) {
return (typeof(numVal) === "number" || typeof(numVal) === "string") && numVal != "" && !isNaN(numVal);
}
var testThis = "123";

//check as follows
alert(is_numeric(testThis));
//returns true

How to check for alphanumeric characters using javascript

Some times before, i was asked by one of my friend to check for alphanumeric characters using javascript. I did it for him using regular expressions.
Following is the code snippet for checking alphanumeric characters.

var testId = "1123ASD";
if((testId.search(/[^a-zA-Z0-9 ]/g)) {
alert("Matched");
}
else {
alert("Invalid");
}
//you can enter characters like + - *^$%^$, etc to check it

I hope this helps someone like me.

08 October, 2010

How to remove al element from array using Javascript

Yesterday, I got into a problem of removing any element from any array in javascript. After some testing, found the solution, thats better for me at least. The following code uses combination of plain javascript and jquery to remove element from an array.
Here is the code.

var arr = ['1', '2', '3'];
var usrId = '2';
//remove an element
arr.splice($.inArray(usrId, arr), 1);

Done

07 October, 2010

How to extend more than one class in php

Since multiple inheritance is not supported in php, we have to find a way to support it, so that we will be
able to extend more than one class at once. For this we can fake multiple inheritance in php using some
class and object functions provided by php.
I came across the problem where i had to extend more than once class using a single class, and for that
after some research came to a solution that can be used to make php support multiple inheritance, if i can say that.

//this is the Abatract class that implements fake multiple inheritance in php
//not allowed to create instance of this class
Abstract class MultipleExtension {

public $_this;
private $_extension = array(); //contains extended classes

//constructor function that passes $this to our private variable $_this
function __construct(){
$_this = $this;
}

//function to add the extended class objects
public function addExtension($obj) {
$this->_extension[]=$obj;
}

//overloading the members with getter function
public function __get($name) {
foreach($this->_extension as $ext) {
//check if the property defined as $name exists in the class $ext
if(property_exists($ext,$name))
return $ext->$name;
}
}

//member overloading using setter function
public function __set($name, $value) {
foreach($this->_extension as $ext) {
//check if the property $name exists in class $ext
//and if it does assign the value in $value to $name property of $ext class
if(isset($ext->$name)) {
$ext->$name = $value;
}
}
}

public function __call($method,$arguments) {
foreach($this->_extension as $ext) {
//check if function exists defined in method variable for the extended class
if(method_exists($ext,$method)) {
//call the user defined function with method and parameters
return call_user_func_array(array($ext, $method) ,$arguments);
}
}
}
}

And below is the implementation of above abstract class that supports multiple inheritance

//this is the first class that sets firstname of a user
class First {
private $_firstName;
public function setName($firstname){
$this->_firstName = $firstname;
}
public function getName(){
return $this->_firstName;
}
}
//this is the second class that sets location of a user
class Second {
private $_locationName;
public function setLocation($location){
$this->_locationName = $location;
}

public function getLocation(){
return $this->_locationName;
}
}
//this is a test class that extends multipleExtension class that fakes multiple inheritance
class Test extends MultipleExtension {
function __construct() {
//call the function that stores all the objects of classes as shown below
parent::addExtension(new First());
parent::addExtension(new Second());
}

public function __toString() {
return $this->getName().' located in: '.$this->getLocation();
}
}
//now create object of Test class and do as follows
$obj = new Test();
$obj->setName("Sudhir");
$obj->setLocation("Nepal");
echo $obj;
//This will output Sudhir located in: Nepal.

27 September, 2010

How to remove non-ascii characters from string

There is a simple way to remove non-ascii characters from a string. This can be used to filter values from POST variables as well. Following line of code does the thing.

$string = "This is a test É";
//replace the non-ascii characters from string with nothing i.e. remove
preg_replace('/[^(\x20-\x7F]*/','',$string);
echo $string;

23 September, 2010

Regular Expressions using Javascript

Sometimes regular expressions can be confusing, but they are great tools for matching a string against a character pattern. They are used for validation of user entry or changing the document content. You can replace a 40 line if/else code with just one line of regular expression. For starters, regular expressions can be fear striking but as you move on with the flow its keeps of getting more and more interesting.
Different languages support regular expressions and they are not as tough as they seem at first sight. Many languages support "find" ,"replace" and "search" feature in regular expressions.
So in this article i will be writing about regular expressions using javascript, to the point that I am also informed to.
Basic Syntax
Let's say you want to search for a string "rain" in a text. You can use two different formats for this.
First is using String Notation


var srchFor = /rain/; //do not use quotation marks
//Second is Object Constructor
var srchFor = new RegExp('rain');
//You can check this as follows:
var str = "When will it rain";
alert(srchFor.test(str));


The expression can be checked using match(), test(), search() or exec() method, all of these are listed later.
Let's say now you want to match a word that starts with some string, in this case, 'rain', you can check this by:


var srchFor = /^rain/;
var srchFor = new RegExp('^rain');
//Or you want to match a word that has just some string and en, in this case, has only 'rain' in it:
var srchFor = /^rain$/;
var srchFor = new RegExp('^rain$');


Here, ^ and $ are starting and ending indicator respectively.
And if want to match a word that ends with some string, in this case 'rain', then


var srchFor = /rain$/;
//Case sensitivity can also be checked. Like,
//if you want to find a word that ends with 'rain' regardless of the case,
//then:
var srchFor = /rain$/i; //Here i refers to case-insensitive
var srchFor = new RegExp('rain$', 'i');


Lets, say we have string that have the word 'rain' several times, now if we want to match a word that is repeated several times, then we can add a global
parameter 'g', doing this will return the matches as array. Such as:

var srchFor = /rain/g; //g refers to global


By default regular expressions match patterns only in single-line strings, so if we want to have a match for multiline strings using regular expressions then 'm' can be used. Such as,

var srchFor = /rain/m; //This matches for rain in multiline

And the parameters can be used in conjunction as well, like,

var srchFor = /rain/igm; OR /rain/gim OR /rain/min; etc in any order

So the above pattern matches 'rain' in multiline,regardless of case and returns array.

Period Character (.)
The dot character means match anything. Such as, match a string that has r at beginning and n at end. Such as,

var srchFor = /r.n/;

The above pattern matches 'ran', 'rin', 'ron', or even r#n or r n, etc.
However you can limt your choices by using square brackets, like

var srchFor = /r[au]n/;

The above pattern matches 'ran' or 'run'.
Exclude you choice, such as match a string excluding some , such as if you want to exclude 'ran' from searcgh then, do the following,

var srchFor = /r[^a]n/;
//But the square brackets match only one character at a time,
//so if you want to match multiple characters then pipes can be used,
var srchFor = /r(^a|u|i|eig|e)/;

This matches 'run', 'rin', 'reigh' and 'ren' but does not match 'ran'.

Escaping Characters
Certain characters need to be escaped, such as: +, /, -, (, ), *, {, }, and ?
Such as /r.n/ matches ran, run, but /r\.n/ only matches "r.n".
Lets us say, you want to validate email address using regular expression, then do the following:


var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;


In above case,
\W is shortcut for [^a-zA-Z0-9_]; match characters that have a to Z characters or 0 to 9 and underscore.
+ means 1 or more times possible
* means 0 or more times possible
? means 0 or 1 times possible
{n} means n times possible
{n,m} means n to m times possible
So,

var srchFor = /^[\W]+(\.[\W]+)*@([\W]+\.)+[a-z]{2,7}$/i;

/^[\W]+(\.[\W]+)* matches sudhi, or sudhi.test
then add @ symbol, then
([\W]+\.) matches oncemore, oncemore.co
then add dot (.),
[a-z]{2,7} means 2 to 7 times the a-z characters are possible.
Other shortcuts are
\d means [0-9] Only integers
\D means [^0-9] All characters but integers
\w means [a-zA-Z0-9_] All alphanumeric characters and the underscore
\W means [^a-zA-Z0-9_] All nonalphanumeric characters
\b means N/A Word boundary
\B means N/A Not word boundary
\s means [\t\n\r\f\v] All whitespace
\S means [^\t\n\r\f\v] No whitespace

Methods Using Regular Expressions
There are several methods that take regular expressions as parameters. The expression itself—
the things inside the slashes or the RegExp constructor—is called a pattern, as it matches what
you want to retrieve or test for.
• pattern.test(string): Returns true or false depending on whether it matches the string
• pattern.exec(string): Returns array on finding match
• string.match(pattern): Returns array of strings on finding match
• string.search(pattern): Matches the string and the pattern and returns the positions and returns -1 if not found
• string.replace(pattern, replaceString): Matches the string against the pattern and replaces every positive match with replaceString.
• string.split(pattern, limit): Matches the string against the pattern and splits it into array



So, Regular expressions only match characters; you cannot do calculations with them. And they are language independent.

22 September, 2010

Map Objects to Database in PHP

Data Mapper Pattern
Since code and database change occurs often during development stage, the separation between domain code and database tends to be beneficial, so that change
in one does not create a need to change the other. There exists a pattern using which we can map objects to database. One probable solution for this can be a
Data Mapper Pattern.
A general idea of the mapper pattern is that a class translates attributes (properties) and methods of domain code to database fields and vice-versa.
Data Mapper is responsible for routing information between domain code and database, creating new domain objects depending on information from database and
updating/deleting information from database depending on information from domain objects.
The mapping between object-oriented code and database can be done in different ways. It can be extracted from XML files, extracting from php array in the class
itself, or hand-coding the correlation in Data Mapper Class. This way implementation of mapping php objects to database is relatively simpler.
Let’s consider an analogy; we have a problem domain for storing user information. So we would generally have two classes; User and UserMapper. So applying the
Data Mapper Pattern we can handle the mapping of objects of User class with database tables and columns using UserMapper Class. For this case we could use an
XML configuration file implementation.
In following xml file, we have “user" as root element that contains a series of field elements as shown below:



id
getId
setId


title
getTitle
setTitle


name
getName
setName



Save the file as uers.xml
The 'name' elements are actually the physical database field name. The .... holds a method "getTitle" to extract attributes.
And .... element holds User method to use when populating the object values. Information regarding creating table structure can also be
added in the xml configuration file, such as type and size of the field. Such information can be particularyl userful when we are creating some kind of
packaged installation script. The information can be used to dynamically create SQL to create database tables. This users.xml file can be read and parsed using
PHP5's SimpleXML functions, like

simplexml_load_file("users.xml");

This XML configuration file will be read by our UserMapper class which acts as Data Mapper in this case. Since Data Mapper Pattern is unobtrusive in nature,
the domain object (User class in this case) remains competely unaware to Data Mapper's (UserMapper Class in this case) existence and due to this reason all the
domain objects (methods) must provided public access to the Data Mapper. In following example, we have Users class, that have all protected attributes but
provides 'get' and 'set ' methods.
Following is our sample Users.php Class

class User {
protected $id;
protected $title;
public function setId($id) {
if (!$this->id) {
$this->id = $id;
}
}
//the following function is called whenever an undefined instance method is called
//name of missing method is passed as first parameter and method arguments as second parameter
public function __call($name, $args) {
if (preg_match("/^(get|set)(\w+)/", strtolower($name), $match)
&& $attribute = $this->validateAttribute($match[2])) {
if ("get" == $match[1]) {
return $this->$attribute;
} else {
$this->$attribute = $args[0];
}
} else {
throw new Exception(
"Undefined method User::".$name."()");
}
}
protected function validateAttribute($name) {
if (in_array(strtolower($name),
array_keys(get_class_vars(get_class($this))))) {
return strtolower($name);
}
}
public function fetch() {
return $this->title;
}
}

And following is our Data Mapper Class

class UserMapper {
protected $conn;
const INSERT_SQL = " insert into users (title, name) values (?, ?)";
const UPDATE_SQL = "update users set title = ?, name = ? where id = ? ";

public function __construct($conn) {
$this->conn = $conn;
foreach(simplexml_load_file("users.xml") as $field) {
$this->map[(string)$field->name] = $field;
}
}
public function save($user) {
$rs = $this->conn->execute(
self::INSERT_SQL
,array(
$user->getTitle()
,$user->getName()));

if ($rs) {
$inserted = $this->findById($this->conn->Insert_ID());
//clean up database related fields in parameter instance
$user->setId($inserted->getId());
}
else {
throw new Exception("Error: ".$this->conn->errorMsg());
}
}
public function findById($id) {
$row = $this->conn->getRow("select * from users where id = ?"
,array((int)$id)
);
if ($row) {
return $this->createUserFromRow($row);
}
else {
return false;
}
}
protected function createUserFromRow($row) {
$user = new User($this);
foreach($this->map as $field) {
$setproperties = (string)$field->presentor;
$value = $row[(string)$field->name];
if ($setproperties && $value) {
call_user_func(array($user, $setproperties), $value);
}
}
return $user;
}
public function add($title, $name) {
$user = new User;
$user->setTitle($title);
$user->setName($name);
$this->save($user);
return $user;
}
protected function insert($user) {
$rs = $this->conn->execute(
self::INSERT_SQL
,array(
$user->getTitle()
,$user->getName()));
if ($rs) {
$inserted = $this->findById($this->conn->Insert_ID());
//clean up database related fields in parameter instance
if (method_exists($inserted,"setId")) {
$user->setId($inserted->getId());
}
}
else {
throw new Exception("DB Error: ".$this->conn->errorMsg());
}
}
public function save($user) {
if ($user->getId()) {
$this->update($user);
}
else {
$this->insert($user);
}
}
protected function update($user) {
$binds = array();
foreach(array("title","name","id") as $fieldname) {
$field = $this->map[$fieldname];
$getproperties = (string)$field->access;
$binds[] = $user->$getproperties();
}
$this->conn->execute(
self::UPDATE_SQL
,$binds);
}
public function delete($user) {
$this->conn->execute(
"delete from users where id = ?"
,array((int)$user->getId()));
}
}
?>

So, in this way using Data Mapper Pattern, we can map php objects to database in a simple way.

20 September, 2010

Collapsible Menu using jQuery

Displaying all information at once to a user is not a good idea. Instead data can
be presented to user as chunks, if it can be said. A good example of displaying
only some data at a time collapsible list. In the following section, i am building
a show/hide list, a collapsible list using jquery.

We will be implementing a list items that contain child lists, and at the beginning
the child lists are hidden, and can be collapsible.

In following html, we can see that List Item 3 has content; so its child list elements
are hidden and mouse cursor changes to hand when hovered. I will explain each section
and then provide a complete working javascript code for collapsible list using jquery.

Select all the LI list items that have list children elements and add click event
handler. The click event handler checks if the target elment of event matches this.

$("li:has(ul)").click(function(event) {
....

When a parent list item in clicked the we check that if its children are hidden by
using jquery is() function.

if ($(this).children().is(':hidden')) {
.....

If the children are hidden, then we show them using show() function, and if they are
already shown we make them hidden by using hide() function. So this makes the list
collapsible. Return false is done to avoid needless propagation.

$(this).children().show();
.....
$(this).children().hide();
...
return false;

Then we change the cursor to pointer and add a click handler to our outermost list
item.

.css('cursor', 'pointer')
.click();
......

The last line makes sure that cursor for those li list items that do not have ul lists
will be default and no image will be added to those lists.

$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});

So this completes our collapsible list using jquery. Furthermore, more css styles
can be added and more jquery features to make it look better.
Following section has complete code for implementation of collapsible menu in jquery.

//head tag start
//include jquery.js script
//script tag start
$(document).ready(function() {
$('li:has(ul)').click(function(event) {
if(this == event.target) {
if($(this).children().is(':hidden')) {
$(this).children().show();
}
else {
$(this).children().hide();
}
}
return false;
})
.css('cursor', 'pointer')
.click();
$('li:not(:has(ul))').css({cursor: 'default','list-style-image': 'none'});
});
//script tag end
//head tag close


  • Item 1

  • Item 2


  • Item 3

    • Item 3.1


    • Item 3.2

      • Item 3.2.1

      • Item 3.2.2

      • Item 3.2.3



    • Item 3.3