Saturday, April 30, 2011

Triple drop down box from database using Ajax with php

triple drop down box from the database without refreshing page using Ajax and PHP. I’ve put three drop down of countries , states and cities and the drop down’s value changes without refreshing the page. Now let show you how to create it quickly.
First create the  tables of country city and states
First create the following tables of country city and states,
 
CREATE TABLE `countries` (
  `id` int(4) NOT NULL auto_increment,
  `countries` varchar(20) NOT NULL default '',
PRIMARY KEY  (`id`)
) TYPE=MyISAM   ;
CREATE TABLE `states` (
 `id` int(4) NOT NULL auto_increment,
 `countryid` int(4) NOT NULL,
`statename` varchar(40) NOT NULL,
PRIMARY KEY  (`id`)
) TYPE=MyISAM   ;
CREATE TABLE `cities` (
`id` int(4) NOT NULL auto_increment,
`city` varchar(50) default NULL,
`stateid` int(4) default NULL,
`countryid` int(4) NOT NULL,
PRIMARY KEY  (`id`)
) TYPE=MyISAM   ;
Now place the following code  in the index.php file
<form method="post" name="form1">
 <table border="0" cellpadding="0" cellspacing="0" width="60%"><tbody>
  <tr>
   <td width="150">Country</td>
   <td width="150"><select style="background-color: #ffffa0" name="country" onchange="getState(this.value)"><option>Select Country</option><option value="1">USA</option><option value="2">Canada</option>       </select></td>
  </tr>
 <tr>
  <td>State</td>
  <td>
  <p id="statediv">
  <select style="background-color: #ffffa0" name="state"><option>Select Country First</option>       </select></td>
</tr>
<tr>
  <td>City</td>
  <td>
  <p id="citydiv">
  <select style="background-color: #ffffa0" name="city"><option>Select State First</option>       </select></td>
</tr>
</tbody></table>
</form>
 
 
in the onChage event of the country drop down getState() function of 
the javascript is called which change the options values the State drop 
down, let’s look at the code the getState() function. 


function getState(countryId)
{
   var strURL="findState.php?country="+countryId;
   var req = getXMLHTTP();
   if (req)
   {
     req.onreadystatechange = function()
     {
      if (req.readyState == 4)
      {
  // only if "OK"
  if (req.status == 200)
         {
     document.getElementById('statediv').innerHTML=req.responseText;
  } else {
       alert("There was a problem while using XMLHTTP:\n" + req.statusText);
  }
       }
      }
   req.open("GET", strURL, true);
   req.send(null);
   }
}
The code of the PHP file findState.php, which populate the options in the drop down of the state which is fetched from Ajax , is given below
<? $country=intval($_GET['country']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('dbname');
$query="SELECT id,statename FROM states WHERE countryid='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?=$country?>,this.value)">
 <option>Select State</option>
  <? while($row=mysql_fetch_array($result)) { ?>
    <option value=<?=$row['id']?>><?=$row['statename']?></option>
  <? } ?>
</select>
In the above states dropdown, getCity() function is called in onChage event with countryId and stateId parameter, now let’s look at the code of the getCity() function
function getCity(countryId,stateId)
{
  var strURL="City.php?country="+countryId+"&state="+stateId;
  var req = getXMLHTTP();
  if (req)
  {
    req.onreadystatechange = function()
    {
      if (req.readyState == 4) // only if "OK"
      {
        if (req.status == 200)
        {
          document.getElementById('citydiv').innerHTML=req.responseText;
        } else {
          alert("There was a problem while using XMLHTTP:\n" + req.statusText);
        }
      }
    }
    req.open("GET", strURL, true);
    req.send(null);
  }
}
In the above ajax function, findcity.php is called and this PHP file populate the city dropdown according to the supplied parameters country and state from get method. Now let’s look at the code of findcity.php,
<?php $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,city FROM cities WHERE countryid='$countryId' AND stateid='$stateId'";
$result=mysql_query($query);
?>
<select name="city">
 <option>Select City</option>
  <?php while($row=mysql_fetch_array($result)) { ?>
 <option value><?=$row['city']?></option>
<?php } ?>
</select>

Sunday, April 17, 2011

Get the Mysql records in Xml format

Introduction
.................................................................................
This tutorial will show you how to take data that is stored in your mySQL database and easily turn it into XML.

$query ="select* from userdetails";
$resultID = mysql_query($query) or die(mysql_error());


$num = mysql_num_rows($resultID) ;
 if ($num != 0) {

 $file= fopen("xml/results.xml","w");

 $_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";

 $_xml .="<userdetails>\r\n";


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


$_xml .="\t<user>\r\n";
$_xml .="\t" . $row["userid"] . "\r\n";

$_xml .="\t\t" . $row["username"] . "\r\n";
$_xml .="\t</user>
\r\n";

}

$_xml .="</userdetails>
";

fwrite($file, $_xml);

fclose($file);

//echo "XML has been written";


} else {

echo "No Records found";

}


?>

Monday, April 4, 2011

Dynamic Site Map using PHP

the sitemap generate based on the directory structure of the site. You can easily exclude files and(or) directories.

The site map is an expandable list, similar to Windows Explorer and is accessible with or without JavaScript enabled on the user's browser. If JavaScript is not enabled, the list is simply displayed in its expanded format so all hyperlinks are visible. Directories and files are sorted alphabetical order . Note that the site map is generated from the file system, not the links contained in the pages.

this script functions by recursively calling itself to traverse the directory tree brgining at the site's root directory. It gets the file title from each file on the site and displays the page title, with a link to the file. Note that the script obtains the title of the page by extracting the text between the opening and closing title tags. That means that it only works on pages that exist (not all the variations that can be generated) and where the title is static and contained in the page.

Demo

Tuesday, March 29, 2011

Lightbox JS v2.05

Lightbox v2.0 uses the Prototype Framework and Scriptaculous Effects Library. You will need to include these three Javascript files in your header.





Include the Lightbox CSS file (or append your active stylesheet with the Lightbox styles).



Check the CSS and make sure the referenced prevlabel.gif and nextlabel.gif files are in the right location. Also, make sure the loading.gif and closelabel.gif files as referenced near the top of the lightbox.js file are in the right location.

Part 2 - Activate

Add a rel="lightbox" attribute to any link tag to activate the lightbox. For example:

image #1

Optional: Use the title attribute if you want to show a caption.
If you have a set of related images that you would like to group, follow step one but additionally include a group name between square brackets in the rel attribute. For example:

image #1
image #2
image #3

No limits to the number of image sets per page or how many images are allowed in each set. Go nuts!
demo

Wednesday, March 9, 2011

Ajax login validation using php &jQuery



View Demo

In this example, first of all we’ll validate the user login detail from ajax showing the messages with some animation. If authenticated, the user will be redirected to the secure page “secure.php”. If you’ll try to directly access “secure.php”, you can’t do that.

Now let’s look at the code how to do this,

HTML Code

< form method="post" action="" id="login_form" />
  < input name="username" type="text" id="username" value="" maxlength="20" />
  < input name="password" type="password" id="password" value="" maxlength="20" />
  < input name="Submit" type="submit" id="submit" value="Login" />
< /form >

As you can see in html code, we’ve created the form with id “login_form”.

And furthermore, the CSS code is same as the one available in the pervious post of checking user availability in ajax and php.

JavaScript Code for Ajax Login validation system in PHP

First of all we need to use the jQuery library in our code,

< script src="jquery.js" type="text/javascript" language="javascript"></script >

Now let’s look at the code in javaScript to call ajax and show the animated message with fading effects.

$("#login_form").submit(function()
{
 //remove all the class add the messagebox classes and start fading
 $("#msgbox").removeClass().addClass('messagebox').text('Validating....').fadeIn(1000);
 //check the username exists or not from ajax
 $.post("ajax_login.php",{ user_name:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
        {
   if(data=='yes') //if correct login detail
   {
  $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
  {
     //add message and change the class of the box and start fading
    $(this).html('Logging in.....').addClass('messageboxok').fadeTo(900,1,
                  function()
    {
           //redirect to secure page
       document.location='secure.php';
    });
  });
   }
   else
   {
    $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
  {
    //add message and change the class of the box and start fading
    $(this).html('Your login detail sucks...').addClass('messageboxerror').fadeTo(900,1);
  });
          }
       });
       return false;//not to post the  form physically
});

As you can see above this code is preety much similar to the previous post of checking username availability in ajax and php and you can see the explanation of the above code from that post. But in above code, where the user is validated, he’ll be logged into the “secure.php” using “document.location” in JavaScript.

$("#password").blur(function()
{
 $("#login_form").trigger('submit');
});

Well, as you can see above javaScript’s code, when focus is moved away from the password it also call the for sumit action. Basically whenever you hit tab button in password field, it starts validating the user detail using ajax.

PHP Code for Ajax Login validation system

First of all lets’s look at the code of the “ajax_login.php”.

//get the posted values
$user_name=htmlspecialchars($_POST['user_name'],ENT_QUOTES);
$pass=md5($_POST['password']);
//now validating the username and password
$sql="SELECT user_name, password FROM tbl_user WHERE user_name='".$user_name."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0)
{
 //compare the password
 if(strcmp($row['password'],$pass)==0)
 {
  echo "yes";
  //now set the session from here if needed
  $_SESSION['u_name']=$user_name;
 }
 else
  echo "no";
}
else
 echo "no"; //Invalid Login

As you can see above, the user login detial is validated from the database. If the user login detail doesn’t exists, it just returns the “no” values and if the user login detial does exists the it just return “yes” values with setting username in session variable.

Finally, let’s look at the code of secure.php

if(empty($_SESSION['u_name']))
  header("Location:index.html");
//if logout then destroy the session and redirect the user
if(isset($_GET['logout']))
{
  session_destroy();
  header("Location:index.html");
}
echo " <a href='secure.php?logout'><b>Logout<b></a> ";
echo " <div align='center'>You Are inside secured Page</a> ";

As you can see above the code of “secure.php” is simpleforward. If the user is not authenticated by session then he’ll be redirected to “index.html”. And there is link for “logout” in this page form where user can destroy the seession.



View Demo

Download Full Source Code





Sunday, February 13, 2011

search key in mongodb

$mat="superman";
 $dd=array('keywords'=>new MongoRegex("/^$mat*/i"));
$cursor = $collection->find($dd);

foreach ($cursor as $obj)
{
$moviename=$obj["moviename"];
}


query display the result where search term is equal to 'superman'





order by clause in mongodb

$dd=array('flag'=>0,'status'=>1);
$s=array( 'id' => -1);
$cursor = $collection->find($dd)->sort($s)->limit(10)->skip(0);

foreach ($cursor as $obj)
{
$username=$obj["username"];

}


  id => -1 means sorting  (desc)  order in mongodb


in sql --->       order by id desc limit 0,10;



Saturday, February 5, 2011

Mongodb

Mongodb is faster than mysql.

it is stored data document orientend.