| 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

| 1 comments ]

tips on error 'Allowed memory size of xxx bytes exhausted'

While working on php, the is chance to get following error "Allowed memory size of xxx bytes exhausted". The reason behind this error is that, Setting the memory limit using the memory limit on the server was exhausted. This is often happens with page with large data, or too many loops, condition checking, or large file uploading etc.

By default the memory limit is 8M we can change this value, by editing the php.ini file. if you are in a dedicated server, we can edit its value on php.ini file and then restart the appache server. But in shared hosting, this issue is very common. usually have no access to php.ini file.

if you have no access to php.ini, we can set these values through coding in php, for that we need to use the following function;

string ini_set(string $apache_variable,string $newvalue);

example :

ini_set('memory_limit','16M');

In some servers we could not do this, in that case we have have an alternative to do this , we just want to use the .htaccess file. we can describe the memory_limit on this file, if there is a .htaccess file, just edit the file and add the desired code.Other wise, create a new one by saving a text file with the name .htaccess, and put it into your working directory.

command

php_value memory_limit [new memory limit]

example

php_value memory_limit 32M

enjoy PHPing.....

| 0 comments ]

1)  set_time_limit();

function to limit the maximum execution time. we can give values starting from zero.the default value is 30 seconds or as per we set on the php.ini file settings. If we given 60 as the time limits the execution will stop when the time reach and return a fatal error.

If we doesn't want to stop the script execution, at any time limit, we can set the function as given below.

set_time_limit(0);


2)  register_shutdown_function('functionname');

The function is used to register a function, while shutdown, like browser closing. We can register multiple shutdown functions. but when we use a exit on any function the functions resisted after that will not execute.

a sample register shutdown function

<?php
function browserClosed()
{
   //we can specify the logout actions on browser closing      
   echo "logout";
}
?>

register_shutdown_function('browserClosed');


3)  ignore_user_abort(bool);

Used to set whether the script should abort, when the client disconnects. if it sets to false, it will abort the script, if its true, it will will not abort the script when the client disconnects.

We can use this function in a situation, when we want to close our browser before the execution completes.

Hope these tips are helpful to you all. Please comment about the posting, I always welcomes your feedback

Enjoy PHPing....

| 0 comments ]

The following example adds/removes text controls dynamically when you click on  add/remove link.
 
 
 
<html>

<head>

<script type='text/javascript'>

function addTxt(txtSid,startDiv,parentDiv,txtArray){

var count=0;

if(document.getElementById(parentDiv)){

var parentObj=document.getElementById(parentDiv);

var divs=document.getElementsByTagName("DIV");

for(i=0 ; i < divs.length ;i++){

if(divs[i].id.indexOf(startDiv)==0 )

count++;

}

new_count=count;

new_count=count+1;

var addDiv = document.createElement('DIV');

addDiv.id =startDiv+new_count;

addDiv.innerHTML = "<input type='text' id='"+txtSid+new_count+"' name='"+txtArray+"[]' value='"+new_count+"'>

&nbsp;<a href=Javascript:removeTxt('"+addDiv.id+"','"+parentDiv+"');>Remove this text #"+new_count+"</a>";

parentObj.appendChild(adddiv);

}

if(document.getElementById(txtSid+new_count)){

document.getElementById(txtSid+new_count).focus();

}

}

function removeTxt(childDiv,parentDiv){

if(document.getElementById(childDiv) && document.getElementById(parentDiv)){

document.getElementById(parentDiv).removeChild(document.getElementById(childDiv));

}

}

</script>

<title>add text control </title> </head>

<body>

<div id="startDiv">

<input type="text" id="txtName1" name=txtGroup[] value="text1" >

</div>

<span><a href="Javascript:addTxt('txtName','startDiv','parentDiv','txtGroup');">Add a text</a></span>

<div id="parentDiv">&nbsp;</div>

</body>

</html>

| 0 comments ]

The following is an example  for simple profile rating
 
 
ratehome.php

<?php

/* you have to get owner and visitor of the profile */

$owner_id=$_REQUEST['owner_id'];

$visitor_id=$_REQUEST['visitor_id'];

$status=$_REQUEST['status'];

$qry=mysql_query("select * from rateProfile where where owner_id=\"$owner_id\" ");

if(mysql_num_rows($qry)>0){

$getrate=mysql_fetch_object($qry);

$cum_rate=$getrate->cum_rate;

$total=$getrate->total;

$val=floor($cum_rate/$total);

}else{

$val=0;

}

if($val==0){

$img='Take the first chance to rate this profile!!!';

}elseif ($val==1){

$img="<img src=\"images/stars1.gif\">";

}elseif ($val==2 ) {

$img= "<img src=\"images/stars2.gif\">";

} elseif ( $val==3){

$img= "<img src=\"images/stars3.gif\">";

}elseif ( $val==4){

$img= "<img src=\"images/stars4.gif\">";

}elseif ( $val==5){

$img= "<img src=\"images/stars5.gif\">";

}

?>

<html>

<head><title>Simple profile rating</title></head>

<body>

<?php

if(isset($_REQUEST['$status']))

{

if($status==1) { ?>

<?php

} elseif($status==2){ ?>

<table align="center" width="550">

<tr><td align=\"center\" colspan=\"2\">You have already rated this profile</td></tr></table>

<?php }

elseif($status==2){ ?>

<table align="center" width="550">

<tr><td align=\"center\" colspan=\"2\">select a rate!! </td></tr></table>

<?php }

}

if($owner_id!=$visitor_id){

?>

<form name='frmRating' action='rateAction.php' method='post'>

<p> Rating: <?php echo $img;?></p>

<p><h1>Rate this profile</h1>

<select name="rates" id='rates'>

<option value="0" selected>Select rating

<option value="1">*

<option value="2">**

<option value="3">***

<option value="4">****

<option value="5">*****

</select>

</p>

<p> The star has the following meaning

<table border=0 cellpadding=3 >

<tr><td align=right>*</td><td>bad</td></tr>

<tr><td align=right>**</td><td>mediocre</td></tr>

<tr><td align=right>***</td><td>good</td></tr>

<tr><td align=right>****</td><td>very good</td></tr>

<tr><td align=right>*****</td><td>excellent</td></tr>

</table> </p>

<p>

<input type='hidden' name='owner_id' value='<?php echo $owner_id;?>'>

<input type='hidden' name='visitor_id' value='<?php echo $visitor_id;?>'>

</p>

<p>

<input type='submit' value='rate!'>

</p>

</form>

<?php } ?>

</body>

</html>

rateAction.php

<?php

/* tables used :2

rateProfile :id(auto_increment,int),

owner_id(int),

cum_rate(int),

total(int): total count of ratings to the profile

rateProfile_history : for storing rating history

id(auto_increment,int),

owner_id(int),

rater_id(int),

rate(int): ratings by the visitor

*/

$conn=mysql_connect("localhost","root","root");
$db=mysql_select_db("dbCommunity");

$owner_id=$_REQUEST['owner_id'];

$visitor_id=$_REQUEST['visitor_id'];

$rate=$_REQUEST['rates'];

if($rate>0){

/* to check whether the visitor has already rated the profile or not */

$qry=mysql_query("select * from rateProfile_history where rater_id='$visitor_id' and owner_id='$owner_id'");

$obj=mysql_fetch_object($qry);

$num=mysql_num_rows($qry);

/* if rated redirect to already rated page*/

if($num==1){

header("location:ratehome.php?owner_id=$owner_id&visitor_id=$visitor_id&status=2");

}else{

($qryt=mysql_query("Select * from rateProfile where where owner_id=\"$owner_id\" ");

$numt=mysql_num_rows($qryt);
if($numt>0){
$add=mysql_query("update rateProfile set cum_rate=cum_rate+$rate,total= total+1 where owner_id=\"$owner_id\" ");
}else{
$add=mysql_query("insert into rateProfile(owner_id,cum_rate,total)values('$owner_id','$rate',1)")or die (mysql_error());
}
$add=mysql_query("insert into rateProfile_history(owner_id,rater_id,rating)values('$owner_id','$rater_id','$rate')")or die (mysql_error());
if($add){
header("location:ratehome.php?owner_id=$owner_id&visitor_id=$visitor_id&status=1");

} }

}else{  header("location:ratehome.php?owner_id=$owner_id&visitor_id=$visitor_id&status=3"); }

?>

 

| 0 comments ]

main.php

<html>
<head><TITLE>Check User Name</TITLE>
<script language="JavaScript" src="jsFile.js" type="text/javascript"></script>
</head>
<body>
<table align="center" border="0">

<TR>
<TD><h3>Check User Name</h3></TD>
</TR>

<TR>
<TD height="10">&nbsp;</TD>
</TR>
<TR>
<TD>Username</TD>
<TD>
<input type="text" name="txtName" id="txtName">
</TD>
</TR>
<TR>
<TD>Password</TD>
<TD>
<input type="text" name="txtpass" id="txtpass">
</TD>
</TR>

<TR><TD colspan='2' align='center'> <span id='resSpan'>&nbsp;</span></TD></TR>

<TR><TD colspan='2' align='center'> <input type='button' value='Check User' onclick='chkLogin()'></TD></TR>
</table>
</body>
</html>


jsFile.js

function chkLogin()
{


var nameVal=$("#txtName").val();
var pwd==$("#txtpwd").val();
var url=checkLogin.php';
var data='name='+nameVal+'&pwd='+pwd;
$.ajax({
type: "POST",
url: url
data: data,
success: function(msg){
document.getElementById('resSpan').innerHTML=msg;
}
});


}


checkLogin.php

<?php

// Db connection edit with your db connection parameters

$conn=mysql_connect("localhost","root","root");
$db=mysql_select_db("dbUserlogs");


$username'=trim($_POST['name']);
$pwd=$_POST['pwd'];

if(!empty($username)){

$sqlqry="SELECT * FROM user_entity where user_name='$username'";
$res=mysql_query($sqlqry) or die(mysql_error());

$count=mysql_num_rows($res);

if($count==0){

$msg='The user '+$username +'does not exist';
}else{

$sqlqry="SELECT * FROM user_entity where user_name='$username' and password='$pwd'";
$res=mysql_query($sqlqry) or die(mysql_error());

$count=mysql_num_rows($res);
if($count==0){
$msg="Incorrect Password!";
}else{


$msg="valid login!";

}

}else{

$msg='Enter username';
}
echo $msg;

?>


| 0 comments ]

The following example will generate random password  for the user name .

main.php

<?php 
$template=<<<T1
<html>
<head><title>Random Passwod Generator </title>
<script language="JavaScript" src="getRandom.js" type="text/javascript"></script>
</head>
<body>
<table align="center"><tr>
                <td colspan='2' align='center'><b>Generate Random Password</b></td>
        </tr>
        <tr>
                <td>User name</td>
                <td>
                        <input type="text" name="txtName" id="txtName">
                        &nbsp;&nbsp;<input type="button" onclick="getRandompwd()" value="Get Password">
                </td>
        </tr>
</table>
</body>
</html>
T1;

echo $template;

?>


getRandom.js

function getRandompwd()
{

var nameVal=$("#txtName").val();
var url='randomPwd.php';
var data='name='+nameVal;
 $.ajax({
   type: "POST",
   url: url
   data: data,
   success: function(msg){
 var respArray = msg.split('+');
if(respArray [0]=="randompwd"){
$("#txtName").val=respArray[1];
 
   }
 });
}


randomPwd.php

<?php

$name=$_REQUEST['name];
$charsArray=array();
$randPwd='';
$pwdLen=10;
$maxLen=25;
$expLen=0;

$chars = "a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z,,@,#,%,&,*,$,1,2,3,4,5,6,7,8,9"; 
$charsArray = explode(",", $chars );

  while($expLen < $maxLen){
           $rands =  rand(0,5);
           $rand_keys .= array_rand($charsArray , $rands);
          $expLen=strlen($rand_keys);
             
        }
      

       $rands=rand(0,9),
       $randPwd= substr($rand_keys,$rands,pwdLen);
        echo 'randompwd'.'+'.$randPwd;

?>

| 1 comments ]


Elgg  is one of the most popular open source social networking platform,which runs on the LAMP(Linux, Apache, MySQL, and PHP)

Elgg offers advanced social networking,user management and administration.And elgg has multiple views that allows for mobile applications and embeddable widgets and the web browser view .Elgg has so many features which makes it as the best cms for social networking sites.It has the features friends ,profiles,avatars, and an editable dashboard with widgets.Elgg installation also provides some optional plugins like blog,file,groups etc by default.All these features(Blogs, profiles, communities, files etc)can be shared among users with access levels(private,public and loggedin) and everything can be cataloged by tags.Since everything in elgg is in the form of plugins, it is very flexible to add your own features in to your elgg site .And it also provides a rich library in its core .

Elgg shared the second best award with drupal , in Open Source Social Networking Content Management System awards 2007. and in 2008 Elgg has been featured as the best opensource networking platform award in InfoWorld's 2008 best of opensource awards.

Now Elgg is very popular and it has been used to power social networks for various institutions and organisations.

Elgg Installation :

Requiremets:

The basic requirements for Elgg is listed belows :

* Apache web server needs to be installed with the following modules,

1)mod_rewrite : This module handles a rule-based rewriting engine to rewrite requested URLs ,This module provides unlimited number of rule conditions ,which allows flexible and powerful URL manipulation mechanism.

2) PHP 5+ with the libraries (GD : dynamic image creation,JavaScript Object Notation for API functionality ,multibyte string support for internationalisation) and also recomends the php modules,SOAP and DOM for some plugins and extra functionality

* For data storage MySQL 5+ is required

Installation process :

You can download thelatest version of Elgg from http://elgg.org. Unzip Elgg and upload the files in to your webserver.

You have to create a data directory to store uploaded files.For the security reasons Elgg suggests that data folder should be at out side of the elgg installation .And must be writable to Elgg.

Create a mysql database and Add a user to the database with all privileges.and access your site through browser .

Elgg will allow you to enter the following settings

dbuser : username for database( with all privileges)

dbpass :dbuser password

dbname :database name

dbhost :host name(generally local host)

dbprefix: the name you would like to prefix Elgg tables(by default it is elgg )

After Entering these settings you need to refresh the page .

Elgg installer will try to create two files automatically for your installation. settings.php, which contains the database settings for your installation and .htaccess file.

If these files can't be automatically generated, Elgg installer will give you these files and you have to save it in correct path (ie engine/settings.php and /.htaccess (in this example elgg is the root folder) )

Incase, this won't work, you have to copy engine/settings.example.php to engine/settings.php , open the file and fill in your database details and Copy /htaccess_dist to /.htaccess .

.If the settings are success elgg will redirect in to a page where you can enter site sdetails and full path to the data directory you have created .then refresh the page

The next page will allow you to enter administrator login details.submit the page .Now you can login using the administrator login.

 Introduction to GUI :

 In the top toolbar, for admin login you can see an administrator link which allows the site administration.

Through the admin panel admin can manage users(user management),can activate/deactivate plugins(Tolls management).

And each user will have a settings menu in top toolbar formanaging individual account settings .

And the top tool bar has a tools menu which is used for navigation along the site.

 Introduction to DB :

 The elgg provides a flexible  data model .You can see the table schema  in the elgg core engine .( engine/schema/mysql.sql).

The tables are automatically generated by the elgg installer on the Database specified by you in the settings .

Main tables :

The dbprefix will be the string which is entred by you in the settings during installation( dbprefix)

dbprefixentities : This is the main Elgg entity table.Elgg defines four basic entity types, ElggSite, ElggUser, elggObject and ElggGroup

dbprefixentity_subtypes : This table contains entity subtype information: For example an elgg object can have subtype blog

dbprefixobjects_entity :This table stores additional information relating to object entities

dbprefixsites_entity :This table stores additional information relating to site entities

dbprefixusers_entity :This table stores additional information relating to user entities

dbprefixgroups_entity :This table stores additional information relating to group entities

dbprefixmetadata : This table containsadditional informations attached to an entity.

dbprefixmetastrings : This table contain the actual string of metadata which is linked to by the metadata and annotations tables

Both tables(metadata&annotation) will have a name_id and a value_id which will be an id from metastring

dbprefixannotations : This table contains annotations (for example comments for discussions/blog is saved as annotations )

dbprefixrelationships :This table defines relationships between two entities.

dbprefixconfig:This table defines config settings.
 

Be an Elggist ;)  good luck :)