Tycoon Talk
Become a Big fish!
The number 1 forum for online business!
Post topics, ask questions, share your knowledge.
Tycoon Talk is part of Freelancer.com - find skilled workers online at a fraction of the cost.

PHP Forum


You are currently viewing our PHP Forum as a guest. Please register to participate.
Login



Freelance Jobs

Closed Thread
Populate triple drop down list from database in PHP
Old 01-08-2010, 02:06 AM Populate triple drop down list from database in PHP
Isabella_Smith's Avatar
Ultra Talker

Posts: 285
Trades: 0
Hi,

I am a newbie in php and needs to populate triple drop down list.

Luckily I got the code but its not working.

Here's the code I am using, please let me know if I mistook somewhere.

Creating tables in database:
PHP Code:
CREATE TABLE `country` (
  `
idtinyint(4NOT NULL auto_increment,
  `
countryvarchar(20NOT NULL default '',
PRIMARY KEY  (`id`)
TYPE=MyISAM   ;

CREATE TABLE `state` (
 `
idtinyint(4NOT NULL auto_increment,
 `
countryidtinyint(4NOT NULL,
`
statenamevarchar(40NOT NULL,
PRIMARY KEY  (`id`)
TYPE=MyISAM   ;

CREATE TABLE `city` (
`
idtinyint(4NOT NULL auto_increment,
`
cityvarchar(50) default NULL,
`
stateidtinyint(4) default NULL,
`
countryidtinyint(4NOT NULL,
PRIMARY KEY  (`id`)
TYPE=MyISAM   
All created successfully.


the index.php file
PHP Code:
<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>

[b]getState() function of the javascript[/b]

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);
   }
}
[b]
The code of the PHP file findState.php.
[/b]

<? $country=intval($_GET['country']);
$link mysql_connect('localhost''root'''); //I changed this to  my database, host, user and password.
if (!$link) {
    die(
'Could not connect: ' mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,statename FROM state 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>

[b]getCity() function[/b]
function getCity(countryId,stateId)
{
  var strURL="findCity.php?country="+countryId+"&state="+stateId;
  var req = getXMLHTTP();
  if (req)
  {
    req.onreadystatechange = function()
    {
      if (req.readyState == 4) // only if "OK"   <--I don't understand this.<--
      {
        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);
  }
}

[b]the code of findcity.php,[/b]

<?php $countryId=intval($_GET['country']);
$stateId=intval($_GET['state']);
$link mysql_connect('localhost''root'''); //I changed this to  my database, host, user and password.
if (!$link) {
    die(
'Could not connect: ' mysql_error());
}
mysql_select_db('db_ajax');
$query="SELECT id,city FROM city 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>
It seems functions isn't working. I select the Country from the combo but it doesn't change the state.


I've done some manual entries in database according the table structure.

Any help would be highly appreciated.
__________________

Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE



Please login or register to view this content. Registration is FREE
buy all indian salwar Kameez, Sarees and clothes

Last edited by chrishirst; 01-08-2010 at 03:07 AM..
Isabella_Smith is offline
View Public Profile
 
 
Register now for full access!
Old 01-08-2010, 03:12 AM Re: Populate triple drop down list from database in PHP
chrishirst's Avatar
Missing! presumed drunk.

Posts: 42,385
Name: Chris Hirst
Location: Blackpool. UK
Trades: 0
Quote:
It seems functions isn't working. I select the Country from the combo but it doesn't change the state.
That's because it can't be done with PHP!

The PHP code is finished when the page is displayed in the browser.

You either have to submit and re-display the page with the changed details or use javascript (AJAX) to link them

http://www.dhtmlgoodies.com/index.ht...chained_select
__________________
Chris. ->>
Please login or register to view this content. Registration is FREE
<<-

A foolish consistency is the hobgoblin of little minds
Thought for today:- Is SEO the only industry where all the cowboys are Indians?
chrishirst is offline
View Public Profile Visit chrishirst's homepage!
 
Old 01-08-2010, 04:00 AM Re: Populate triple drop down list from database in PHP
Isabella_Smith's Avatar
Ultra Talker

Posts: 285
Trades: 0
Quote:
Originally Posted by chrishirst View Post
That's because it can't be done with PHP!

The PHP code is finished when the page is displayed in the browser.

You either have to submit and re-display the page with the changed details or use javascript (AJAX) to link them

http://www.dhtmlgoodies.com/index.ht...chained_select

Thanks for your help chrishirst, I think I've used ajax in js function.

Code:
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);
   }
}
Please let me know if this is wrong, I am also considering the link you gave me.

Thanks
__________________

Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE
|
Please login or register to view this content. Registration is FREE



Please login or register to view this content. Registration is FREE
buy all indian salwar Kameez, Sarees and clothes

Last edited by chrishirst; 01-08-2010 at 04:09 AM..
Isabella_Smith is offline
View Public Profile
 
Old 01-08-2010, 04:10 AM Re: Populate triple drop down list from database in PHP
chrishirst's Avatar
Missing! presumed drunk.

Posts: 42,385
Name: Chris Hirst
Location: Blackpool. UK
Trades: 0
Use code tags please http://www.webmaster-talk.com/php-fo...st-my-php.html

It looks ok at a glance over.
__________________
Chris. ->>
Please login or register to view this content. Registration is FREE
<<-

A foolish consistency is the hobgoblin of little minds
Thought for today:- Is SEO the only industry where all the cowboys are Indians?
chrishirst is offline
View Public Profile Visit chrishirst's homepage!
 
Old 07-28-2010, 09:23 AM Re: Populate triple drop down list from database in PHP
Junior Talker

Posts: 2
Trades: 0
Hi,
Know this is an old post but thought I'd post a reply anyway.

I used this code myself just a few days ago and got it working ok.
I think the only thing wrong is you haven't changed the db name to your db name.
This line in the findstate and findcity pages:
mysql_select_db('db_ajax');
needs to be changed from db_ajax to the name of your database where all your tables are stored.

Hope this helps.

Last edited by chipowski; 07-28-2010 at 09:25 AM.. Reason: reply was too vague
chipowski is offline
View Public Profile
 
Old 07-28-2010, 09:35 AM Re: Populate triple drop down list from database in PHP
Junior Talker

Posts: 2
Trades: 0
Also noticed that your index.php contents do not look complete.
If you change the db name and use the full listing from below, it should work ok for you.

HTML Code:
<html>
<head>
<title>Roshan's Triple Ajax dropdown code</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - [email]nepaliboy007@yahoo.com[/email]
// If you have any problem contact me at [url]http://roshanbh.com.np[/url]
function getXMLHTTP() { //fuction to return the xml http object
        var xmlhttp=false;    
        try{
            xmlhttp=new XMLHttpRequest();
        }
        catch(e)    {        
            try{            
                xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                try{
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch(e1){
                    xmlhttp=false;
                }
            }
        }
             
        return xmlhttp;
    }
    
    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);
        }        
    }
    function getCity(countryId,stateId) {        
        var strURL="findCity.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);
        }
                
    }
</script>
</head>
<body>
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="150">Country</td>
    <td  width="150"><select name="country" onChange="getState(this.value)">
    <option value="">Select Country</option>
    <option value="1">USA</option>
    <option value="2">Canada</option>
        </select></td>
  </tr>
  <tr style="">
    <td>State</td>
    <td ><div id="statediv"><select name="state" >
    <option>Select Country First</option>
        </select></div></td>
  </tr>
  <tr style="">
    <td>City</td>
    <td ><div id="citydiv"><select name="city">
    <option>Select State First</option>
        </select></div></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
</table>
</form>
</body>
</html>

Last edited by chrishirst; 07-28-2010 at 06:03 PM..
chipowski is offline
View Public Profile
 
Closed Thread     « Reply to Populate triple drop down list from database in PHP
 

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are Off





   
RSS Feed  Feeds: RSS   JS   XML
RSS Feed  Feeds for this forum: RSS   JS   XML



Page generated in 0.58596 seconds with 12 queries