| 0 comments ]

How to set up .htpasswd in a site ?

Step 1 : create file .htpasswd and put out side our root folder but inside www for safety.

Step 2 : open the file .htpasswd and add like username:password -> then save and close. So now file contains

   username:password

Step 3 : Add the following in .htaccess file

AuthName "Restricted Area"
AuthType Basic
AuthUserFile D:/wamp/www/.htpasswd # full path to .htpasswd file
AuthGroupFile /dev/null
require valid-user


----------

Now open you site http://mysite.com
It will ask username and password to display.

Use this functionality in all admin side. It will block all hackers.

Posted by : Shijith Nambiar

| 1 comments ]

Redirecting a domain into an another directory of same level

Consider there is a domain called mydomain.com, which curretly pointed to a directory named 'folder1' in the home directory(public_html). Now, I just want to redirect this domain to an another directory, which is in the same home folder(public_html named 'folder2'

In this case we could use the following htaccess code, just remember that you have included the 'RewriteEngine On' statement at the beginning of the htaccess file

RewriteCond %{HTTP_HOST} ^mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$
RewriteCond %{REQUEST_URI} !^/folder2/
RewriteRule (.*) /folder2/$1

Now the when type mydomain.com/folder2 it will redirect the folder named 'folder2' in which the directory level the folder 'folder1' is. Not to the subfolder of folder1.

Another case of usage of htaccess redirect.

For setting an HTML splash page for your domain.


if you want to redirect all the traffic to the domain mydomain.com/ to a new folder named /anothersub, but you want to keep the other existing subfolders of mydomain.com/ working as they act

RewriteCond %{HTTP_HOST} ^mydomain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.mydomain\.com$
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) /anothersub/index.html

In this case the traffic to mydomain.com will go to mydomain.com/anothersub/index.html instead of mydomain.com/index.html.
but the traffic to mydomain.com/subfolder1 , mydomain.com/subfolder2, blah blah .. will go to corresponding pages as usual.

| 0 comments ]

Adding cron tasks in Linux using SSH

in most hosting platforms we have the control panel console to add cron tabs. But in the case of our local linux machine, or server's which does not have control panel, we could use the following

adding the commands in the crontab

Login in the console as super user

Use the following command " sudo crontab -e " to open the crontab file.
Some times you will get a message to select the editor to open the file. select the desired editor. the crontab file will open and it contains the syntax for the crontab command. its looks like " # m h dom mon dow command "

m -> minute
h -> hour
dom -> date of month
mon -> Month
dow -> day of week

for setting cron for every minute use the following code

* * * * * yourcommand

for each five minutes

*/5 * * * * yourcommand

For hourly cron

0 * * * * yourcommand

For daily cron

0 0 * * * yourcommand

for yearly

0 0 1 1 * yourcommand


we could also run the cron in particular minute ,hour etc.

15,45 * * * yourcommand

the cron will run each 15 and 45 min of every hour

0 12,24 * * yourcommand

the cron will run each 12 and 24 every hour


where the value of * holds value "Every".


After setting the cronjob save the cron tab file.


For testing these cronsettings please follow following steps..

create the php script and save as mycron.php

root","root");
mysql_select_db("crontest");
$date = date("Y-m-d H:i:s");
mysql_query("INSERT INTO `test`(`timer`) VALUES ('$date')");
?>

create corresponding database and table

CREATE TABLE IF NOT EXISTS `test` (
`id` int(11) NOT NULL auto_increment,
`timer` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
) ENGINE=MyISAM



open crontab file add following command


*/5 * * * * php /pathto/mycron.php

and save the file and check back the mysql table for inserted values.

I hope this post will help you know details about adding cron job without the control panel or plesk console in your server or in the local machine

| 0 comments ]

Running php script on command line & installing php5-cli library in phpserver

To run php in command line, you need to not only PHP, but also the PHP5-cli library in your php server. The PHP5-cli stands for command-line interpreter for the PHP5 scripting language. It is very useful when we need test our scripts from the shell. In some cases we need to install this library for running cronjobs on the server.


how to install php5-cli. in linux machines.


first login as super user : " su username "

after login just use the following command "sudo apt-get install php5-cli "

the php5-cli installation has completed

just restart your apache server. For that we can use the following command

How to restart a apache server on linux

sudo /etc/init.d/apache2 restart

After the restart of your server, the php5-cli has been installed on your server. and just try to run a simple php script on your server.

| 0 comments ]

/*******************************/
# function to get the byte format #
# @phpqa.blogspot.com #
/*******************************/

function getByteFormat($number,$caption="small"){

$unit = "";
switch($number){

case($number >= 1099511627776):

$number = round($number / 1099511627776, 1);
$unit = $caption == "small" ? "TB" : "Terabyte";
break;

case($number >= 1073741824):

$number = round($number / 1073741824, 1);
$unit = $caption == "small" ? "GB" : "Gigabyte";
break;

case($number >= 1048576):

$number = round($number / 1048576, 1);
$unit = $caption == "small" ? "MB" : "Megabyte";
break;

case($num >= 1024):

$number = round($number / 1024, 1);
$unit = $caption == "small" ? "KB" : "Kilobyte";
break;

default:
$unit = $caption == "small" ? "B" : "Byte";
$number = $number;
break;

}

return number_format($number, 2).' '.$unit;

}

# How to use #

echo getByteFormat(10995116277,"big");
echo getByteFormat(109951162799,"small");
echo getByteFormat(10995116261099);

?>

please try this function and lemme give your feedback as comments

| 2 comments ]


function get_url(){

$server = empty( $_SERVER["HTTPS"] ) ? '' : ( $_SERVER["HTTPS"] == "on" ) ? "s" : "";

$root= substr( strtolower ( $_SERVER["SERVER_PROTOCOL"] ), 0,
strpos( strtolower( $_SERVER["SERVER_PROTOCOL"] ), "/") ) . $server;

$root .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$root.= $_SERVER["SERVER_NAME"]. " : " .$_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$root.= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
}
return $root;

}

| 0 comments ]

The following function will help you to create a thumbnail for an image.

function get_thumb($img_filename, $maxwidth, $maxheight) {

$img_size = getimagesize($img_filename) ;

if($img_size) {

$width = $img_size [0];

$height = $img_size [1];

$thumb_height=$ height;

$thumb_width=$width;

if ($width > $maxwidth) {

$thumb_width = $maxwidth;

$thumb_height = floor($height * ($maxwidth / $width));

}

if ($thumb_height > $maxheight) {

$thumb_width = floor($thumb_width * ($maxheight / $thumb_height));

$thumb_height = $maxheight;

}

if ( (imgsizearray['mime']== 'image/jpeg')|| (imgsizearray['mime']== 'image/png')|| (imgsizearray['mime']== 'image/gif')) {

$type=explode('/', $imgsizearray['mime']);

$thumb_image = imagecreatetruecolor($thumb_width, $thumb_height);

$image ="imagecreatefrom" . $type[1] ($img_filename);

if($image){


/*Copy and resize part of an image with resampling*/

imagecopyresampled($thumb_image, $image, 0,0,0,0,$thumb_width,$thumb_height,$width,$height);

}

imagejpeg($thumb_image, null, 100);

}

}

return false;

}

you can call the function like this . get_thumb ($file,100,100);

$img_filename is the uploaded file,and $maxwidth and $maxheight are the height and width specification for thumb

| 1 comments ]

CAPTCHAs are used to prevent automated software from performing actions.CAPTCHAs have several applications for practical security, including Preventing Comment Spam in Blogs, Preventing Comment Spam in Blogs,CAPTCHAs also offer a plausible solution against email worms and spam.

The following is an example for securing a form with captcha

main.php

<?php

require_once('functions.php');

If($_POST){

If(validate_captcha()){

echo "captcha okay";

//do your actions here

else{

echo " captcha not okay";

}

}

}else{

mt_srand ((double)microtime()*1000000);

$maxran = 1000000;

$random = mt_rand(0, $maxran);

$html = "<html>

<header><title>form with captcha</title></header>

<body> <form name='frm' action='' method='post'>";

$html.="name:<input type='text' name='txtname'>";

$html.="password:<input type='password' name='txtpwd'>";

$html .= "<div id=\"Registercode\"><table><tr><td><img src='". create_captchaImg.php?ran=".$random." ></td> ";

$html .= "<td><input type=\"text\" name=\"captchacode\" maxlength=\"10\" /></td></tr></table></div>";

$html .= "<input type='hidden' name='randomcode' value='". $random."'>

<input type='submit' name='submitbtn' value='submit' >

</form>

";

echo $html;

}

?>

functions.php

<?php

/* function to generate captcha code */

function generate_captcha($num) {

$timemd5=md5($num);

$date = date('F j');

$year=date('Y');

$temp=md5($num . $date.$year . $timemd5);

$capcode = hexdec($temp);

$code = substr($capcode, 4, 6);

return $code;

}

/* function to validate captcha*/

function validate_captcha() {

$captchacode = $_POST['captchacode'];

$randomcode = $_POST['randomcode'];

$generated_code = generate_captcha($randomcode);

$valid = false;

if ((trim($captchacode) != "") && (strcmp($captchacode, $generated_code) == 0))

$valid = true;

else

$valid=false;

return $valid;

}

?>

create_captchaImg.php

<?php

/* function to generate captcha image with the captcha code.choose some image as background */

require_once('functions.php');

$ccode=$_REQUEST['ran'];

$capcode = $ccode;

$code = generate_captcha($capcode);

$image = ImageCreateFromJPEG("images/captchabg.jpeg");//give captcha background image path

$text_color = ImageColorAllocate($image, 80, 80, 80);

Header("Content-type: image/jpeg");

ImageString ($image, 5, 12, 2, $code, $text_color);

ImageJPEG($image, '', 75);

ImageDestroy($image);

}

?>

| 2 comments ]

Function to find out last 12 months details from the current date

function getLast12MonthsDetails(){

        $month = date('m');
        $year  = date('Y');
        $i = 1;
        $date = a rray();
        while($i<=12){
          $timestamp = mktime(0,0,0,$month,1,$year);
          $date[$i]['month']      = date('F', $timestamp);
          $date[$i]['monthCount'] = date('m', $timestampts);
          $date[$i]['monthShort'] = date('M', $timestamp);
          $date[$i]['daysInMonth'] = date('t', $timestamp);
          $date[$i]['year']      = date('Y', $timestamp);
          $date[$i]['yearShort']  = date('y', $timestamp);
          $month--;
          $i++;
        }
        return $date;
    }


calling the function

print_r(getLast12MonthsDetails());

will return the following details in an array

Array
(
[1] => Array
(
[month] => July
[monthCount] => 12
[monthShort] => Jul
[daysInMonth] => 31
[year] => 2009
[yearShort] => 09
)

[2] => Array
(
[month] => June
[monthCount] => 12
[monthShort] => Jun
[daysInMonth] => 30
[year] => 2009
[yearShort] => 09
)

[3] => Array
(
[month] => May
[monthCount] => 12
[monthShort] => May
[daysInMonth] => 31
[year] => 2009
[yearShort] => 09
)

[4] => Array
(
[month] => April
[monthCount] => 12
[monthShort] => Apr
[daysInMonth] => 30
[year] => 2009
[yearShort] => 09
)

[5] => Array
(
[month] => March
[monthCount] => 12
[monthShort] => Mar
[daysInMonth] => 31
[year] => 2009
[yearShort] => 09
)

[6] => Array
(
[month] => February
[monthCount] => 12
[monthShort] => Feb
[daysInMonth] => 28
[year] => 2009
[yearShort] => 09
)

[7] => Array
(
[month] => January
[monthCount] => 12
[monthShort] => Jan
[daysInMonth] => 31
[year] => 2009
[yearShort] => 09
)

[8] => Array
(
[month] => December
[monthCount] => 12
[monthShort] => Dec
[daysInMonth] => 31
[year] => 2008
[yearShort] => 08
)

[9] => Array
(
[month] => November
[monthCount] => 12
[monthShort] => Nov
[daysInMonth] => 30
[year] => 2008
[yearShort] => 08
)

[10] => Array
(
[month] => October
[monthCount] => 12
[monthShort] => Oct
[daysInMonth] => 31
[year] => 2008
[yearShort] => 08
)

[11] => Array
(
[month] => September
[monthCount] => 12
[monthShort] => Sep
[daysInMonth] => 30
[year] => 2008
[yearShort] => 08
)

[12] => Array
(
[month] => August
[monthCount] => 12
[monthShort] => Aug
[daysInMonth] => 31
[year] => 2008
[yearShort] => 08
)

)

From the above array, we can get all the details of last 12 months.
hope that this will helpful for you guys.

happy PHPing

I wish, you guys, please comment about this post in following box.

| 0 comments ]

The river is an activity stream containing descriptions of activities. In new elgg there is a plugin called “riverdashboard” , And you can add river for your plugins too.Each river may be added after an activity such as add delete etc .You can use the following function for doing this.

add_to_river($viewname,$actionname,$userguid,$entityguid);

The first parameter $viewname is the name of the view that will display the river item and the next one $actionname is the action and the other two parameters are the guid of the user performing the action, and the guid of the entity being acted on.

Elgg recommends the view location of the river views as follows /river/classname/event, where classname is the class you’re interested in (ElggObject for objects, ElggUser for users, and so on) and event is the event (create, update, delete and so on).

River item information will be passed in an object called $vars['item'], which contains two important parameters $vars['item']->subject_guid that is the user guid and the action guid that is the $vars['item']->object_guid .

| 2 comments ]

I would like to share some basics about plugin development in elgg .

In elgg all the plugins will be in mod directory. You can drop your plugin in this directory.

First you need a name for your plugin.The names of the plugins in an installation must be unique.


you need a ‘start.php’ file for each plugin which to describe the common functions for a plugin.This file can be considered as the core controller of all plugins .The start.php must have an init function which initializes the plugin .

You have to register this function to elgg system and have to make sure the initialisation function is called on initialisation.

The following is a sample if the init functuion is yourplugin_init()

register_elgg_event_handler('init','system',’yourplugin _init');


In common the elgg plugin will have following folders

actions : Commonly all action(normally form actions) files are saved in this folder.

And you can register all the actions involved in a plugin with in its start.php file

The function is as follows .

register_action($action, $public = false, $filename = "", $admin_only = false)

For example

register_action('blog/add',false,$CONFIG->pluginspath . "blog/actions/add.php");

the parameters of the register_action indicates

action : The name of the action (here "blog/add")

second parameter is a Boolean parameter.which indicates whether the action is public or not that is whether this action be accessed by people not logged into the system or not.In above example false indicates that it is not a public action.

Next is filename that is where the action is located here the action is located in blog/actions/add.php , $CONFIG->pluginspath gives the path to plugin s that is the full path to mod directory of your elgg installation .

And if it is required you can register the action as admin action .you have to set the fourth parameter as true for this by default it in false.


Views : In common all html files will be in this folder .You can call these views in the plugin using the function

elgg_view(‘viewname’,$array_of params)

You can override existing views also.The view lodes based on the plugin priority.

You can extend views using the function extend_view('original view ','your view');


The view folder contains a default folder which holds all the views of plugin .For the easiness .For the easiness you can use subfolders in the default folder.

For example if you have a plugin named blog and it have a view called create.php in the path views /defaults/blogs/create.php you can call this view like ‘blogs/create ‘ .That is you can call the view as follows elgg_view(‘blogs/create’)

Language file :

This file contains the language translations for the plugin.

Creating Friendly URLS:

You can create nice URLs for your plugin using page handler function.for doing this you have to define and register a page handler in `start.php`,


function handlerfunction($page) {

switch ($page[0])

{

case 'index':

Your code for the index view

break;

case 'your_view':

include(‘yourview’);

break;

}

}

register_page_handler(handler, 'handler_function’);

in this function the first argument handler is your entity type, the next argument is the your plugin function handling the request which will get passed as an array in `$page` this carries each url segments. You can check for a location and can create the cases corresponding to that.



User settings:

Plugins might have some settings , You can create the view in the file settings.phpand you can retrieve the settings by the following function

get_plugin_setting($name, $plugin_name );

and you can set values using

set_plugin_setting($name, $value, $plugin_name);function

You can create widgets on your plugins .The widget might be in the folder views/default/widgets

The widgets folder may have two files one is view.php that is view of widget and the other is eidt.php that is the page for setting the widget display options like number of items to be displayed etc.

You can initialize the widget in the init function using the following function

add_widget_type('widgettitle',$name_of_widget,$desc_of_widget) .

| 1 comments ]

Hello ,

I am Bibin John, fromKerala. I have seen you in a facebook group 'Php Developers in KERALA'
This mail is regarding an issue ,that i am facing with php. I have a php website In this site there is a feedback form, when I submit that form It shows an error like this,:
Parse error: syntax error, unexpected T_STRING in /home/tecwand/public_html/contact.php on line 1

I am using cpanel accelerated hosting , PHP5.2.8. I think the problem with this version. My friend using 5.2.6 in cpanel, but no problem with the same PHP script that I used!
Below I mentioned the PHP script I used , Can you make its syntax suitable for php 5.2.8 ?

<?php
$name=$_REQUEST['name'];
$email=$_POST['email'];
$comment=$_POST['comment'];
$con=mysql_connect("localhost","root","");
mysql_select_db("tecwand",$con);
$ins="insert into comments values('$name','$email','$comment')";
mysql_query($ins);
echo"inserted";
?>
Hope that you will help me!
Kindly make replay to this e mail address!

Thanks and Regards,
Bibin John


| 0 comments ]

The MYSQL joins are explained below with examples

Inner Join( Equi-Join)
In the inner-join the columns of two tables. It can be used to select certain fields from both tables and only the correct rows will be joined together.

Syntax:

SELECT <column_name> FROM <Table1>, <Table2> WHERE (Table1.column = Table2.column)  

xample :

SQL query:

SELECT test1.id, test1.name, test2.id, test2.favcolor
FROM test1, test2
WHERE (
test1.name = test2.name

)


Id

name

id

favcolor

1

sree

1

black

2

divs

2

white


Cross- Join

Cross-join of two tables takes data of each row in table1 and joins it to the data from each row in table2.

Syntax: SELECT <column_names> FROM <table1>, <table2>

Example :

test1

Id

Name

1

Sree

2

divs

3

dev


test2

Id

favcolor

Name

1

black

Sree

2

white

divs

SQL query:

SELECT test1.id, test1.name, test2.id, test2.favcolor
FROM test1, test2



id

name

id

favcolor

1

sree

1

black

2

divs

1

black

3

dev

1

black

1

sree

2

white

2

divs

2

white

3

dev

2

white


Left Join &Right join

Left Join

according to the match condition.It will show all values from left table whether there is amatching value in right or not

Syntax:

SELECT <column_name> FROM <Table1> [join|LEFT JOIN |RIGHT JOIN ] <Table2> on  (Table1.column = Table2.column)  

for example consider the following two tables

testtable1


eid

eName

eBasicpay

1

sree

200000

2

divs

500000

3

vid

000000

testtable2

id

eid

phone

1

1

987654

2

3

322352362

3

5

1222222


example :

SQL query:

normal join will show a result like this


select eName , eBasicpay, phone

from testtable1     join testtable2   on testtable1.eid  =  testtable2.eid  


eName

eBasicpay

phone

sree

200000 

987654

vid

 1000000 

322352362


The result of left join is    SELECT eName, eBasicpay, phone
FROM testtable1
LEFT JOIN testtable2 ON testtable1.eid = testtable2.eid


eName

eBasicpay

phone

sree

200000 

987654

divs

500000  

NULL

vid

 1000000 

322352362


Right join

according to the match condition.It will show all values from right table whether there is amatching value in left or not

example :

SQL query:

SELECT eName, eBasicpay, phone
FROM testtable1
RIGHT JOIN testtable2 ON testtable1.eid = testtable2.eid


eName

eBasicpay

phone

sree

200000 

987654

vid

500000  
322352362

NULL

NULL
1222222



You can use 'USING' clause on the Left /Right Join , if the columns that are carrying out the join on have the same name.

Syntax:

SELECT <column_name>  FROM <Table1>  LEFT JOIN <Table2>  USING (<column_name>) example :

SQL query:

SELECT *
FROM testtsable1
LEFT JOIN testtsable2 using(eid)

eid

eName

eBasicpay

id

eid

phone

1

Sree

200000

1

1

987654

2

div

500000

NULL

NULL

NULL

3

vid

500000

2

3

322352362

Joining three tables   for example take the following table as the third table   testtable3

id

eid

favcolor

1

1

black

2

2

blue

3

5

green

SQL Query
SELECT *
FROM testtsable1
LEFT JOIN testtsable2 ON testtsable1.eid = testtsable2.eid
LEFT JOIN testtsable3 ON testtsable1.eid = testtsable3.eid

eid

eName

eBasicpay

id

eid

phone

id

eid

favcolor

1

Sree

200000

1

1

987654

1

1

black

2

div

500000

NULL

NULL

NULL

2

2

blue

3

vid

500000

2

3

322352362

NULL

NULL

NULL

  


Good Luck :)

| 0 comments ]

* create_function :

This function will create a php function .This function returns a unique function name as a string, or FALSE on error on creation.

Syntax :create_function( string $argument_list , string $function_code )

for example
<?php
$addnumbers = create_function('$no1,$no1', 'return "sum = " . $no1+$no2;');
echo $addnumbers(12,100) . "\n";
?>

output

sum=112


* function_exists


This function can be used to check whether a function is defined or not .It teturn true if the function has been defined

for example


<?php

function myfunction(){
echo "Reached here";
}

$fun='myfunction';
echo function_exists($fun)?" function $fun exist <br>":" $fun doesn't exist <br>";

$fun='myfunction11';
echo function_exists($fun)?" function $fun exist <br>":" $fun doesn't exist <br>";
?>

output :
function myfunction exist
function myfunction11 doesn't exist


* is_callable()

this function checks whether a variable can be called as a function or not


* call_user_func

This function call a user function

syntax: call_user_func ( function ,parameter)


for example


<?php
function egfunction(&$age){
echo $name."\n";
$age++;
}
$age=22;
echo "my age before function call ".$age;
call_user_func('egfunction', $age);
echo "my age after function call ".$age;
?>

output :

my age before function call 22
my age after function call 23


* call_user_func_array

this function call a function with an array of parameters.
for example


<?php

function myfunction($no1, $no2) {
return $no1+ $no2;
};

$func='myfunction';
echo call_user_func_array($func, array(300,500));

?>

output

800


* func_num_args :

This function returns the number of arguments passed to the function,
This function can be used with func_get_arg() and func_get_args() to ensure that the right number of arguments have been passed to a function.

for example


<?php
function sampleFn()
{
$argNo = func_num_args();
echo "Number of arguments: $argNo \n";
}

sampleFn();
sampleFn('only one arg');
sampleFn('two', 'args');
sampleFn(1,2,3,4,5,6,7,8,9,10);
?>

output :

Number of arguments : 0
Number of arguments : 1
Number of arguments : 2
Number of arguments : 10

Note : in javascript we can use arguments.length to find the length
alert(arguments.length);


* func_get_arg

This function returns an item from the argument list.

syntax : func_get_arg ( $num )


<?php
function myfunction()
{
$No = func_num_args();
echo "Number of arguments: $No<br />\n";
if ($No >= 2) {
echo "Third argument is: " . func_get_arg(2) . "<br />\n";
}
}

myfunction ('v1','V2','V3','V4');
?>

output :
Third argument is V3


* func_get_arg

<?php
function myfunction()
{
$no = func_num_args();
echo "Number of arguments: $numargs<br />\n";
$args = func_get_args();
for ($i = 0; $i < $no; $i++) {
echo "Argument". $i+1." is: " . $args[$i] . "<br />\n";
}
}

myfunction ('v1','V2','V3','V4');
?>


output

Argument 1 is V1
Argument 2 is V2
Argument 3 is V3
Argument 4 is V4

| 0 comments ]

UNION can be used to combine two or more result sets from select statements into a single result set.

Syntax :

<SELECT statement1> UNION [DISTINCT | ALL] <SELECT statement2> UNION [DISTINCT | ALL]


for example consider the following tables


SELECT * FROM table1;


----------------------------------------------
| name1 | name2 | add1 |
--------------------------------------------
| Princy | Peter | R/220 V st |
--------------------------------------------
| Joban | John | R/456 Mst |
--------------------------------------------


SELECT * FROM table2;
------------------------------------
|Company | Address |
-------------------------------------
|TCS | 24/cChennai|
-------------------------------------
|Cubet | 43C EKM |
------------------------------------


SELECT * FROM table3;

-------------------------------------------------
|studname1|studname2|address |
-------------------------------------------------
| aarathi | Sharma | 122c/Nst|
--------------------------------------------------
| Sagar | C | 143c/Nst|
------------------------------------------------
|Sree | Nithya | 132c Dst |
-------------------------------------------------

mysql Query :

SELECT name1 , name2, addr1 FROM table1
UNION
SELECT Company, "", Address FROM table2
UNION
SELECT studname1, studname2, address FROM table3;



Result will be

---------------------------------------------------
| name1 | name2 | add1 |
----------------------------------------------------
| Princy | Peter | R/220 V st |
----------------------------------------------------
| Joban | John | R/456 Mst |
----------------------------------------------------
| TCS | | 24/cChennai |
-----------------------------------------------------
|Cubet | | 43C EKM |
-----------------------------------------------------


Union all is the default in UNION and Distinct can be used to avoid the duplication in selection



Good Luck :)

| 3 comments ]

Pattern Matching in mysql

My sql provides two functions LIKE and NOTLIKE for Simple pattern matching

LIKE

Syntaxt for using like is expr

LIKE <pattern >

The Like provides '%' and _ as patterns

For example consider following table

sampletable
---------------------------------
|fname | lname |
------------------------------
| Joban | John |
-------------------------------
| Neena |T |
-------------------------------
| James| Mathew |
-------------------------------
|sreejitha|M |
-------------------------------
| Nitha | sree |
------------------------------

different types of patters using like


SELECT * FROM sampletable WHERE fname LIKE 'J%';

This will select first and 3rd row from the above table .

---------------------------------
|fname | lname |
------------------------------
| Joban | John |
-------------------------------
| James| Mathew |
------------------------------


SELECT * FROM sampletable WHERE fname LIKE '%J%';

output

---------------------------------
|fname | lname |
------------------------------
| Joban | John |
-------------------------------
| James| Mathew |
-------------------------------
|sreejitha|M |
-------------------------------

Next we can use five '_' to get records in which fname has 5 letters
SELECT * FROM sampletable WHERE fname LIKE '_____';

output

---------------------------------
|fname | lname |
------------------------------
| Joban | John |
-------------------------------
| Neena |T |
-------------------------------
| James| Mathew |
-------------------------------
| Nitha | sree |
------------------------------

REGEXP :

It matches a pattern with regular expression

Following is the pattern which can be used along with REGEXP

* a '.' can be used for any single character.

* s set of character in "[...]" matches any character within the brackets.

* "*" matches zero or more instances of the thing preceding .

* can use "^" at the beginning or "$" at the end of the pattern.

* + 1 or more

* ? 0 or 1

* {n} exactly n

* {n,} n or more

* {n,m} between n and m

* | either, or

* [^...] Any character not listed between the square brackets


some sample queries are shown below.

* for the names containing a "j" we can use the query
SELECT * FROM sampletable WHERE fname REGEXP 'j';

* for the names beginning with J we can write a query as follows
SELECT * FROM sampletable WHERE fname REGEXP '^J';

* for the nameending with 'a' we can write a query like
SELECT * FROM sampletable WHERE fname REGEXP 'a$'

* for the name with four characters we can use the query
SELECT * FROM sampletable WHERE fname REGEXP '^....$';
(or)
SELECT * FROM sampletable WHERE fname REGEXP '^.{4}$'

* Query to find all the names starting with a vowel and ending with 'y'
SELECT * FROM sampletable WHERE fname REGEXP '^[aeiou]|y$';





Enjoy :)

| 1 comments ]

MySQL INDEX

A database index is a data structure that improves the speed of operations in a table.Indexes are also can be considered as a type of tables which keeps primary key or index field and a pointer to each record in to the actual table.The users cannot see or use the indexes defined on tables , they are used by Database Search Engine to locate records very fast.

When you create a new index MySQL builds a separate block of information that needs to be updated every time there are changes made to the table. This means that if you are constantly updating, inserting and removing entries in your table this could have a negative impact on performance.

Indexes help us to find data faster. It can be created on a single column or a combination of columns. A table index helps to arrange the values of one or more columns in a specific order.

* Allow the server to retrieve requested data, in as few I/O operations
* Improve performance
* To find records quickly in the database

for example


CREATE TABLE sampletable (id INT, fname VARCHAR(50), lname VARCHAR(50), INDEX (id))

Simple and Unique Index:
in this type of indexing two rows cannot have the same index value

syntax :CREATE UNIQUE INDEX ON ( column1, column2,...);

CREATE UNIQUE INDEX F_INDEXON tab1 (tab2)


Points to consider for optimizing the MySQL Indexes

* The columns with the most unique and variety of values should be used.
* Smaller the index better the response time.
* For functions that need to be executed frequently, large indexes should be used.
* Avoid use of index for small tables.


Good Luck :)

| 0 comments ]


function trim_array($array){
$newarray= array();
$i = 0;
foreach ($array as $key => $value) {
if (!empty($value)) {
$newarray[$i] = $value;
$i++;
}
}
}

function trim_array_restorekey($array){
foreach ($array as $key => $value) {
if (empty($value)) {
unset($array[$key]);
}
}

return $array;
}

$sourseArray=array("0"=>"Black",
"1"=>"blue",
"2"=>"",
"3"=>"green",
"4"=>"",
"5"=>"pink",
);

echo "Sourse array
";

print_r($sourseArray);

echo "
Remove Empty locations of array with out key restoration
";

print_r(trim_array($sourseArray));
echo "
Remove Empty locations of array with key restoration
";

print_r(trim_array_restorekey($sourseArray));
?>
output :

Source array

array("0"=>"Black",
"1"=>"blue",
"2"=>"",
"3"=>"green",
"4"=>"",
"5"=>"pink",
);

Remove Empty locations of array with out key restoration

array("0"=>"Black",
"1"=>"blue",
"2"=>"green",
"3"=>"pink",
);

Remove Empty locations of array with key restoration

array("0"=>"Black",
"1"=>"blue",
"3"=>"green",
"5"=>"pink",
);

| 0 comments ]

MySQL stored procedure:

It is a block of code stored on the server which executes a set of MySQL statements which increases performance of application.Once created, stored procedure is compiled and stored in the database catalog. It reduced the traffic between application and database server because instead of sending multiple uncompiled commands statement, application only has to send the stored procedure name and get the result back.It is reusable to any application

disadvantages of stored procedures

Stored procedure make the database server high load in both memory for and processors.
it only contains declarative SQL so it is very difficult to write a procedure with complexity of requirement


CREATE PROCEDURE myproc()
BEGIN
SELECT FROM tab;
END


MySQL Triggers

MySQL trigger is a piece of code that fires whenever an event occures to a table.The event can be a DML statement such as

delete - the trigger fires whenever 'delete' command executes on the table
insert - the trigger fires whenever 'insert' command executes on the table
update - the trigger fires whenever the table is updated

The trigger may be fired before the event occurs or after the event occurs


When creating a trigger you need to specify four pieces of information:

The unique trigger name
associated table
The event that the trigger should respond to (DELETE, INSERT, or UPDATE)
When the trigger should be executed (before or after processing)

CREATE TRIGGER trigger_name
ON table_name
FOR EACH ROW
BEGIN

END

create database tabdb
use tabdb
create table tab1(int val1);
create table tab2(int val2);
create table tab3 ( int val3 auto_increment PRIMARY KEY);


CREATE TRIGGER tabtrig BEFORE INSERT ON tab1
FOR EACH ROW BEGIN
INSERT INTO tab1 SET val1 = NEW.val1;
DELETE FROM tab3 WHERE val3 = NEW.val1;
END;

Advantages of using triggers

Using a trigger You can use them to check for, and prevent, bad data entering the database
you can catch the errors in business logic in the database level.
trigger provides an alternative way to run scheduled tasks. you can handle those tasks before or after changes being made to database tables.
A trigger generally performs the types of tasks described faster than application code, and and can be activated easily and quickly behind the scenes and does not need to be a part of your application code

While trigger is implemented there are some restrictions like following:

it's not allowed to call a stored procedure in a trigger.
It's not allowed to create a trigger for views or temporary table.
It's not allowed to use transaction in a trigger.
'Return' is not possible with a trigger.
triggers for a database table must have unique name. It is allowed that triggers for different tables having the same name but it is
recommended that trigger should have unique name in a specific database.

A stored procedure can only be run by some one or something and that's where the MySQL trigger is used.MySQL triggers are simple, effective, way of managing data in a database - the database user needs to be aware of the entering data and if stored procedures are used then the programming will take care of everything else.


| 2 comments ]

Running a perl script from PHP
I have tried to run a perl script from my php file. The perl script was running in command line and worked well.
But when I tried to execute the same form my php script, it was not working . I have tried the same with the other possibilities system, passthru, shell_exec, exec, etc. I have used the following commands.

shell_exec("perl filename.pl arg1");
shell_exec("user/bin/perl filename.pl arg1");

I have tried out with both paths of perl script and perl compiler and even tried with out path of compiler. But no luck :(..result was the same

Do you face the same problem? Try out the following.I have tried the same and my perl script worked well from php

* Turn On the safe mode settings in your php.ini file
You need to check whether the safe mode is ON in your php settings( php.ini).
You can use phpinfo() to check the same . If it is set OFF please set it as ON.
This is needed to run the shell execution commands in php.

* Check permission of perl script
It is required to give give all permissions to web server on the perl script (user owner and user group). if your web
server is apache, you need to set the user owner and user group to apache.Now the peal script execution from php will work. if you have the sudo permission you can do it yourself.

if you run the system("perl filename.pl arg1"); with out proper permission it will return an error code 13, which is related to the file permission.

Now your perl script will work fine from php . you can try it out with all execution commands .

passthru("perl filename.pl arg1");
exec("perl filename.pl arg1");
or $var = `perl filename.pl arg1`;


I hope this will help someone else which is my reason for sharing

enjoy scripting .....

Please comment me regarding on the post.

| 0 comments ]


<?php

// function to calculate the elapsed time from microtime

function elapsedTime($startTime = '', $endTime = '',$format="SECONDS",$decimals = 4)
    {
       
        if (!$startTime)
        {
            return '';
        }

        if (!$endTime)
        {
            $endTime = microtime();
        }
   
        list($startMicroSecond, $startSecond) = explode(' ', $startTime);
        list($endMicroSecond, $endSecond) = explode(' ', $endTime);
       
        //number_format(($em + $es) - ($sm + $ss), $decimals);
       
        if($format){
            $format = strtoupper($format);
        }
        if($format == 'SECONDS'){       
            $timeVal  =  number_format((($endMicroSecond + $endSecond) - ($startMicroSecond + $startSecond)),$decimals)." SECONDS";
        }
        else if($format == 'MINUTS'){
            $timeVal  =  number_format((($endMicroSecond + $endSecond) - ($startMicroSecond + $startSecond))/60 ,$decimals). " MINUTS";
        }       
        else if($format == 'HOURS'){
            $timeVal  =  number_format((($endMicroSecond + $endSecond) - ($startMicroSecond + $startSecond))/3600,$decimals). " HOURS";
        }
        else if($format == 'DAYS'){       
            $timeVal  =  number_format(((($endMicroSecond + $endSecond) - ($startMicroSecond + $startSecond))/3600)/24,$decimals)." DAYS";
        }       
       
        return $timeVal;       
    }
   
   
    // How to use ....
   
    $a = "0.85969200 1242372611";
    $b = microtime();
   
   
    // examples    
   
    echo '<p>Elapsed Time  in Days: '.elapsedTime($a,$b,"DAYS",2).'</p>';
    echo '<p>Elapsed Time  in Hours: '.elapsedTime($a,$b,"HOURS",2).'</p>';
    echo '<p>Elapsed Time  in Minuts: '.elapsedTime($a,$b,"MINUTS",2).'</p>';
    echo '<p>Elapsed Time  in Seconds: '.elapsedTime($a,$b,"SECONDS",2).'</p>';
   
    // only starting time
   
    echo '<p>Elapsed Time  in Hours: '.elapsedTime($a,'',$format="HOURS",6).'</p>';
   
    // start time only with no format and no decimel positions
   
    echo '<p>Elapsed Time  in Seconds: '.elapsedTime($a).'</p>';
   
   
?>


enjoy PHPing

| 1 comments ]


<?php

// function to check whether the year given is a leap year or not

function checkLeapYear($year){
// Is the year a leap year?
if ($year % 400 == 0 OR ($year % 4 == 0 AND $year % 100 != 0))
{
return true;
}
else{
return false;
}
}

$a = 2003;
if(checkLeapYear($a)){
echo "Leap Year";
}
else{
echo "Not a leap Year";
}
?>


enjoy PHPing

| 1 comments ]

Some of the common php array functions are explained with simple examples

* array() :
Creates an array
* array_count_values():
It returns an array, with ,the parent array's values as keys, and the values is the number of occurrences.

Example:




$alphas = array('A', 'B', 'C', 'D', 'B', 'C', 'C', 'D', 'E');

$result = array_count_values($alphas);
print_r($results);
echo "
The array alphas have $result[A] A's, $result[B] B's, $result[C] C's,$result[D] D's and $result[E] E's";


?>

Output:


Array ( [A] => 1 [B] => 2 [C] => 3 [D]=>2 [E]=>1 )
The array alphas have 1 A's, 2 B's, 3 C's,2 D's and 1 E's


* array_change_key_case :
returns an array with all array keys in specified case.
the array Constants CASE_LOWER and CASE_UPPER used with this function. The former returns the array key values in lower case(default case) the later returns the array key values in upper case.

Example:


$parent=array("a"=>"apple","B"=>"boy","c"=>"cat","d"=>"doll");
$result=array_change_key_case($parent,CASE_UPPER);
?>

Output:


Array ( [A] => apple[B] => boy [C] => cat [D]=>doll)


*array_chunk() : splits an array into new arrays.
This function has 3 parameters one is array itself second one is size of chunk and third one is preserve_key which determines whether to preserve the parent key or not .
true value preserves the keys and false does not preserve the keys.False is the default one.

Example:


$array=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
$result1=array_chunk($array,2);
$result2=array_chunk($array,2,true);
echo "The result array1=> preserve_key=default ie false ";
print_r($result1);
echo "
The result array2=> preserve_key=true "

print_r($result2);
?>

Output:

The result array1=> preserve_key=default ie false
Array (
[0] => Array ( [0] => apple[1] => boy )
[1] => Array ( [0] => cat [1] => doll )
)
The result array2=> preserve_key=true

Array (
[0] => Array ( [a] => apple[b] => boy )
[1] => Array ( [c] => cat [d] => doll )
)

*array_flip :
this function will transposes the keys and values of an array

Example:

$array=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");

echo "Array before using the flip function
";

foreach($array as $key=>$value){

echo "
array[".$key."]=>".$value;

}
$flipped_array = array_flip($array);

echo "Array after using the flip function
";

foreach($flipped_array as $key=>$value){
echo "
flipped_array[".$key."]=>".$value;

}

Output:

Array before using the flip function

array[a]=>apple
array[b]=>boy
array[c]=>cat
array[d]=>doll

Array after using the flip function


flipped_array[apple]=>a
flipped_array[boy]=>b
flipped_array[cat]=>c
flipped_array[doll]=>d

* array_intersect :
this function returns an array containing elements that are present in all array arguments.
it returns with the key of first arry.

Example:

$array1 = array('apple', 'boy', 'cat', 'doll');
$array2 = array('doll','angel', 'bag', 'car');
$array3 = array('art', 'brain', 'doll', 'coal');
$intersect = array_intersect($array1, $array2, $array3);
echo "Intersection of array1, array2 and array3 is ";
print_r($intersection);
?>

output :
Intersection of array1, array2 and array3 is

Array
(
[3] => doll
)


* array_diff() :
this function returns an array with the keys and values from the first array, if the value is not present in the other arrays

* array_diff_assoc() :the function returns an array with the keys and values from the first array, only if they are not present in the other arrays

example :

$array1=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
$array2=array("a"=>"apple","b"=>"bag",c=>"doll","d"=>"cat");
$result=array_diff($array1,$array2);
echo "
out put by array_diff()";

print_r($result);
echo "
out put by array_diff_assoc() ";

print_r(array_diff_assoc($array1,$array2));
?>
output:

out put by array_diff()";

Array (
[b] => boy
)


out put by array_diff_assoc()

Array (
[b] => boy
[c]=>cat
[d]=>doll
)

* array_combine() :
creates an array by merging two other arrays, with the first array as the keys, and the other as the values

example:


$array1=array("a","b","c","d");
$array22=array("apple","boy","cat","doll");
$result=array_combine($array1,$array2);
echo "merged array";
print_r($result);
?>
.output:

merged array

Array (
[a] => apple
[b] => boy
[c] => cat
[d] => doll

)



* array_keys() :
returns all valid keys for the given array.
* array_values() : returns an array containing all the values of an array

example:


$array1=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
echo "
Array keys
", implode(", ", array_keys($array1));

echo "
Array values";

print_r(array_values($array1));

?>
Array keys

a, b,c,d

Array values
Array ( [0] =>apple [1] => boy [2] => cat [3]=>doll )

* array_merge()
:merges arrays into one array

example :

$array1=array("a"=>"apple","b"=>"doll");
$array2=array("c"=>"cat","b"=>"boy");
print_r(array_merge($array1,$array2));
?>
output

Array (
[a] => apple
[b] => boy
[c] => cat
)

* array_reverse() :returns an array in the reverse order .The second parameter determines whether to preserve the key of the parent array or not

example :

$array1=array("a"=>"apple","b"=>"boy","c"=>"cat","d"=>"doll");
print_r(array_reverse($array1));
?>
output

Array (
[d] => doll
[c] => cat
[b] => boy
[a]=>apple
)


*array_walk() : runs each array element in a user-defined function


example


function userFn($value,$key)
{
echo "array1[".$key."]=>".$value;
}
$array1=array("a"=>"apple","b"=>"doll");
array_walk($array1,"userFn");
?>


output :

array1[a]=>apple
array1[b]=>doll


*array_slice : returns an array subset of consecutive elements from the parent array




$array=array(0=>"apple",1=>"boy",2=>"cat",3=>"doll");
print_r(array_slice($array,-2,1));
echo "
";

print_r(array_slice($array,1,2,true));
?>

Array ( [0] => cat )

Array ( [1] => boy [2] => cat )

* arsort() : sorts an array by the values in reverse order
* ksort() : Sorts an array by key
* krsort() : Sorts an array by key in reverse order


$array = $array1=array2=array("a"=>"cat",b"=>"boy","c"=>"apple","d"=>"doll");
echo "arsort
";

arsort($array );
print_r($array );
echo "asort
";

asort($array1 );
print_r($array1 );
echo "ksort
";

ksort($array2 );
print_r($array2 );
?>
output
arsort
Array
(
[d]=>doll
[a] => cat
[b] => boy
[c] => apple
)

asort
Array
(
[c] => apple
[b] => boy
[a] => cat
[d]=>doll
)

ksort
Array
(
[a] => cat
[b] => boy
[c] => apple
[d]=>doll
)
krsort
Array
(
[d]=>doll
[c] => apple
[b] => boy
[a] => cat



)



* sizeof() : Returns the number of array elements.
* range() : Automatically create an array containing a range of elements
* in_array() : Returns true or false if an array contains a specific value.

example:

$array = array("a"=>"cat",b"=>"boy","c"=>"apple","d"=>"doll");
echo "size of array:".sizeof($array );
echo "
";

if (in_array("apple",$array ))
{
echo "Apple is in array";
}
else
{
echo "Apple is not in array";
}
?>
output :
sizeof array :4
* extract() : Extracts list items into matched variable/value pairs
* list() : Assigns list values to variables.
* shuffle() : Shuffles an array


$array1 = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
echo "Before shuffling ", implode(", ", $array1 ), "\n";
shuffle($array1 );
echo "After shuffling ", implode(", ", $array1 ), "\n";
?>

Output:

Before shuffling: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
After shuffling : 9, 4, 6, 3, 1, 5, 7, 8, 2, 10