Question

chain selectboxes again

Asked by: ellandrd

any chance of getting this to work?

our senerio:

ive got 3 fields in a table called location, title and jobtype

i want to have 3 select boxes and have them dynamically populate based on the selectbox selections.

example 1:

if i select location = Aberdeen, then the titles selectbox will be populated with titles where location = Aberdeen
or if i select location = Dublin, then the titles selectbox will be populated with titles where location = Dublin...

exmaple 2:

if i select location = Aberdeen, I should get all titles where location = Aberdeen. then say i pick title = Programmer from that aberdeen title list, then the jobtypes selectbox will be populated with jobtypes where location = Aberdeen and title = Programmer...

remember these values are coming from a database table and not a predefined array...

can this be done and how?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-08-01 at 02:13:52ID21938769
Tags

select

,

chain

Topic

PHP Scripting Language

Participating Experts
4
Points
500
Comments
51

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. selectbox and checkboxes
    hi everyone... i have a form in which i have a group of checkboxes and a selectbox i have a js which populates the selectbox with the value of the checkbox when it is checked and when it is unchecked the js removes the option from the selectbox. but i have another function ...
  2. ADD OPTIONS DYNAMICALLY TO SELECTBOX
    i have 3 checkboxes and a selectbox if the checkboxes are checked some values need to be populated in the selectbox but if the selectbox has that value already it should not add them. suppose checking the checkboxA u shud add options a,b,c,d checking checkboxB u shud add opt...
  3. chain selectboxes
    im not too sure how to approach this but what im trying to do is the following: I have a access database table containing a location field and a title field and are both memo datatypes. the location field contains locations - Aberdeen, Edinburgh, Glasgow, Stirling, Dundee, ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: ljubiccicaPosted on 2006-08-01 at 03:13:36ID: 17222314

that is exactly what AJAX does...

=)

http://en.wikipedia.org/wiki/AJAX

Hope it helps

 

by: ellandrdPosted on 2006-08-01 at 03:21:32ID: 17222355

but how?  ive already tried some AJAX examples and cant get any to work..

can you help me code one please?

 

by: _Maddog_Posted on 2006-08-01 at 03:38:04ID: 17222432

Hi ellandrd,

I wrote my first Ajax app after reading this tutorial.
Maybe it'll help you as well :)

http://rajshekhar.net/blog/archives/85-Rasmus-30-second-AJAX-Tutorial.html

- Maddog

 

by: ellandrdPosted on 2006-08-01 at 03:40:26ID: 17222443

i have came across alot of tut's like this on matte what i try i cant get what i want working hence why i keep asking for help... but everyone seem to just ppint me towards learning AJAX and AJAX tut's which isnt helping me...

 

by: ljubiccicaPosted on 2006-08-01 at 04:07:48ID: 17222563

the reason: when you'll learn AJAX, you'll know everything about it and will be able to do it next time...

yes, we want points from you but you'll keep comming again and againg if somebody gives you code for everything...

=)

 

by: ellandrdPosted on 2006-08-01 at 04:33:42ID: 17222698

>>yes, we want points from you but you'll keep comming again and againg if somebody gives you code for everything...

look in my profile...  

i dont expect somebody to code a complete application for me...I can program myself, but each time ive tried to code this application, i cant get it working... i need to get help/advice from you if your willing to provide it...

 

by: ldbkuttyPosted on 2006-08-01 at 04:43:56ID: 17222742

There are four options (3rd option is what you wanted):

(1) Server-Side: If you need to get the data for the second drop down box data from the database then re-parse the page to the web server. (i.e.) You can use onchange="this.form.submit()" in you first drop-down box and populate the next dropdown box based on the previous dropdown selections. The disadvantage of this method is it might take long time and/or might be inconvenient when there are other numerous form-fields. Here's my answer based on server-side: http:Q_21260505.html#12948858

(2) Client-Side: Query the database initially and store all results in a JS array. Then, you can use onchange="jsFunction()" in your first drop-down box, where jsFunction() is the JavaScript function that actually populates the second drop-down based on the selected value and the pre-defined JS array. Its better to do it on server side if your total count of option combinations is greater then two thousand combinations, because JavaScript function needs to have ALL data at browser side. Here's my previous similar question: http:Q_21103384.html Its infact very easier to generate JavaScript array based on Query result sets.

(3) JSRS: JavaScript Remote Scripting with which you dont need to worry about the number of combinations of options and page reloading. Here are the links:

http://www.ashleyit.com/rs/
http://www.ashleyit.com/rs/jsrs/select/php/select.php

(4) Frames: Have every selection box in a frame and populate based on the previous frame selection box values selections. But Frames is not a good solution comparing others.

 

by: ellandrdPosted on 2006-08-01 at 04:57:17ID: 17222815

ldbkutty

this is what i need - thank you..

the demo in option 3 is what im after, but i cant tel if the select options are been read from db or js array?
 

 

by: ldbkuttyPosted on 2006-08-01 at 05:40:10ID: 17223141

The options are read remotely from the DB through Javascript. As stated, download the files and and modify select_rs.php (http://www.ashleyit.com/rs/jsrs/select/php/select_rs.php.txt) as required. Once you are able to run the example, it shouldn't be difficult to make it work for your application.

 

by: nschaferPosted on 2006-08-01 at 05:42:15ID: 17223158

Here's yet another tutorial.  This one is actually based on ASP, not PHP, but can be easily modified to PHP.

I wrote this tutorial, so I'd be happy to help you with any problems you have along the way.

http://www.applicationgroup.com/tutorials/MultiDropDownXMLHTTP.asp

Hope this helps,

Neal.

 

by: ellandrdPosted on 2006-08-01 at 06:18:07ID: 17223430

hi nschafer,

I would like to stay with PHP as i cant code in ASP...  i will look at your tut...

 

by: ellandrdPosted on 2006-08-01 at 06:21:36ID: 17223452

Neil - does the values in the select boxes come from database each time?

its a long tuturial so i will take a closer look in a few mins...

 

by: nschaferPosted on 2006-08-01 at 06:50:01ID: 17223717

Yes, the data come from a database.  When you select an option from the first select box an AJAX call is made to determine what options are available for the second select box.  When you select an option from the second selet box an AJAX call is made to determine what options are available for the third select box, and so forth.

The ASP part of the code in my sample is minimal and I can help you convert it to PHP.  I'm by no means a PHP expert, but I can certainly get at least this going.

Neal.

 

by: ellandrdPosted on 2006-08-01 at 06:59:15ID: 17223800

OK.. well im still working on your tutorial and the tutorial ldbkutty gave me...

 

by: ellandrdPosted on 2006-08-01 at 07:34:14ID: 17224144

ldbkutty

I have that demo working and but im not sure how to go about changing it to suit what i need?

it uses 3 tables...i only use 1: tblJobs and it is as follows:

job_id | location | title                |    jobtype
    1    |   ABZ     |  Programmer  |    contract
    2    |   ABZ     |  Engineer        |    Permanent
    3    |   LDN     |  Administrator |    contract

can you help me?

 

by: ldbkuttyPosted on 2006-08-01 at 08:08:21ID: 17224536

Try with this select_rs.php:

<?php

require("jsrsServer.php.inc");
jsrsDispatch( "makeList modelList optionsList" );

function makeList () {
  return serializeSql("select location, location from tblJobs order by location" );
}

function modelList ($loc) {
  return serializeSql("select title, title from tblJobs where location='{$loc}' order by title");
}

function optionsList ($loc='', $title='') {
  return serializeSql("select jobType, jobType from tblJobs where location='{$loc}' and title='{$title}' order by jobType");
}

function serializeSql( $sql ){
  $link = mysql_connect("localhost", "mysql", "mysql");
  mysql_select_db ("selectdemo");
 
  $result = mysql_query ($sql);
  $s = '';
  while ($row = mysql_fetch_row($result)) {
   $s .= join( $row, '~') . "|";
  }
 
  mysql_close($link);
  return $s;
}
   
?>

and change the cbFillOptions function in select.php.js file to this:

function cbFillModel ( strModels ){
  // callback for dependent listbox
  window.status = '';
  fillList( 'lstModel',  strModels );
  if(IDModel != noValue){
    var params = [''+IDMake+'', ''+IDModel+''];
    jsrsExecute( 'select_rs.php', cbFillOptions, 'optionsList', params);
  }
}

 

by: nschaferPosted on 2006-08-01 at 08:33:58ID: 17224806

ellandrd,

  It looks like you're working with another tutorial, which is great, but I just wanted to let you know that I added the appropriate PHP code to the tutorial I listed above.

Neal.

 

by: ellandrdPosted on 2006-08-01 at 09:26:34ID: 17225378

>>I added the appropriate PHP code to the tutorial I listed above.

excellant - the more tut's the better...

 

by: ellandrdPosted on 2006-08-01 at 09:32:03ID: 17225430

ldbkutty

ive made those changes but my drop downs are just blank now

 

by: ellandrdPosted on 2006-08-01 at 09:36:35ID: 17225488

nschafer

it is possible to see how you build your database/table?

 

by: nschaferPosted on 2006-08-01 at 10:47:35ID: 17226252

The database used for my example is using an MS-Access database.  Here is the structure

ID          AutoNumber
Year       Number
Make      Text
Model     Text
Engine    Text

An example of the data is below.
ID      Year      Make      Model                         Engine
29      2002      Mercury      Mystique                      4 Cylinder
30      2002      Mercury      Grand Marquis      6 Cylinder
31      2002      Mercury      Grand Marquis      8 Cylinder
32      2002      Lexus      ES300                      6 Cylinder
33      2002      Lexus      GS300                      6 Cylinder
34      2002      Lexus      GS300                      8 Cylinder
35      2002      Lexus      SC300                      4 Cylinder

Neal.

 

by: ellandrdPosted on 2006-08-01 at 11:36:54ID: 17226735

yes this is like mine... i will try implement your example in a  few mins...

 

by: ellandrdPosted on 2006-08-01 at 11:55:08ID: 17226890

Dont seem to work:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>XMLHTTP Test</title>
<script>
function getHTTPObject() {
      var req = false;
      // branch for native XMLHttpRequest object
      if(window.XMLHttpRequest) {
            try {req = new XMLHttpRequest();}
            catch(e) {req = false;}
      // branch for IE/Windows ActiveX version
      } else if(window.ActiveXObject) {
            try {req = new ActiveXObject("Msxml2.XMLHTTP");}
            catch(e) {
              try {req = new ActiveXObject("Microsoft.XMLHTTP");}
              catch(e) {req = false;}
            }
      }
      return req;
}

function fill(sel) {
      oHttp = getHTTPObject();
      if (oHttp.readyState != 0) {oHttp.abort();}
      var yr_sel = document.getElementById('yr');
      var mk_sel = document.getElementById('mk');
      var mod_sel = document.getElementById('mod');
      var style_sel = document.getElementById('style');
      var sel_to_fill = document.getElementById(sel);

      //clear all selects from the one we are filling on
      //make the vars we need for the argument string
      switch(sel){
        case 'yr':      yr_sel.options.length = 0;
            case 'mk':            mk_sel.options.length = 0;
            case 'mod':            mod_sel.options.length = 0;
            case 'style':      style_sel.options.length = 0;
      }

      var mod = ""
      var mk = ""
    var yr = ""
      if (yr_sel.options.length > 0) yr = yr_sel.options[yr_sel.selectedIndex].value;
      if (mod_sel.options.length > 0) mod = mod_sel.options[mod_sel.selectedIndex].value;
      if (mk_sel.options.length > 0) mk = mk_sel.options[mk_sel.selectedIndex].value;
      var sURL = "MultiDropDownXMLHttp2.asp";
      sURL += "?year=" + yr + "&make=" + mk + "&model=" + mod;
      oHttp.open("get", sURL , true);

      oHttp.onreadystatechange = function () {
            if (oHttp.readyState == 4) {
                  var options = oHttp.responseText.split(",");
                  sel_to_fill.options[0] = new Option("Choose One:","");
                  for (i=1;i<=options.length;i++) {
                        sel_to_fill.options[i] = new Option(options[i-1],options[i-1]);
                  }
            }
      }
      oHttp.send(null);
}
</script>
<style type=text/css>
.lbl {width:50px;float:left;}
</style>
</head>
<body>
<form method="post" name="frmCars">
<div class="lbl">Year:</div><select name="yr" id="yr" onchange="fill('mk');" ></select><br />
<div class="lbl">Make:</div><select name="mk" id="mk" onchange="fill('mod');"></select><br />
<div class="lbl">Model:</div><select name="mod" id="mod" onchange="fill('style');"></select><br />
<div class="lbl">Engine:</div><select name="style" id="style"></select><br />
<input type=submit />
<script>fill("yr")</script>
</form>
</body>
</html>
<?php
/* ------------------ */
/*  Create SQL Query  */
/* ------------------ */
if (!isset($_GET["year"])) {
  $sql = "Select distinct [year] From tblCars Order by Year";
}
elseif (!isset($_GET["make"])) {
  $sql = "Select distinct Make From tblCars" .
         " Where year = " . $_GET["year"] .
         " Order by Make";
}        
elseif (!isset($_GET["model"])) {
  $sql = "Select distinct Model From tblCars" .
         " Where year = " . $_GET["year"] .
         "   and make = '" . $_GET["make"] . "'" .
         " Order by model";
}        
else {
  $sql = "Select distinct Engine From tblCars" .
         " Where year = " . $_GET["year"] .
         "   and make = '" . $_GET["make"] . "'" .
         "   and model = '" .$_GET["model"] . "'" .
         " Order by engine";
}
/* --------------- */
/*  Open Database  */
/* --------------- */
$db = new COM("ADODB.Connection");
$datapath= substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],'\\')) . "\db.mdb";
$ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" . $datapath;
$db->open($ConnStr);

/* --------------- */
/*   Get Records   */
/* --------------- */
$rs = $db->execute($sql);
$output = "";
while (!$rs->EOF) {
  if (!$output == "") $output = $output . ",";
  $output = $output . $rs->fields[0];
  $rs->movenext;
}

/* ----------------- */
/*   Close Database  */
/* ----------------- */
$rs->close;
$db->close;

/* ------------------ */
/*   Display Output   */
/* ------------------ */
echo $output
?>

 

by: ellandrdPosted on 2006-08-01 at 11:56:24ID: 17226906

im trying to run it on apache under:

W:\Apache\htdocs\sandpit\JSRS\db.mdb
W:\Apache\htdocs\sandpit\JSRS\index.php

in my URL i have: http://localhost/sandpit/JSRS/index.php

 

by: ellandrdPosted on 2006-08-01 at 12:01:39ID: 17226957

also what would this be in PHP:

<%
' This section is just to display the results. Normally you
' would submit to another page, or have this page save the
' results to a database.

if request.form("yr") > "" then
response.write("<b>You Selected: </b><br />")
response.write("Year: " & request.form("yr") & "<br />")
response.write("Make: " & request.form("mk") & "<br />")
response.write("Model: " & request.form("mod") & "<br />")
response.write("Engine: " & request.form("style") & "<br />")
response.write("<input type=button value='Close Window' onclick='window.close();' />")
response.end
end if
%>

 

by: nschaferPosted on 2006-08-01 at 12:02:27ID: 17226966

Do you get any error messages?  If so what.

Note that the above should be two seperate files.

The php code goes into a seperate file and the file name is used in the fill function

    var sURL = "MultiDropDownXMLHttp2.asp";

in place of MultiDropDownXMLHttp2.asp

Neal.

 

by: ellandrdPosted on 2006-08-01 at 12:04:32ID: 17226988

>>Do you get any error messages?  If so what.

none, all i get is my 4 selectbox. if i try select anything, they are blank.

>>Note that the above should be two seperate files.

yes i know.  I have my HTML page called index.php and PHP code in a page called MultiDropDownXMLHttp2.php (not .asp)

 

by: nschaferPosted on 2006-08-01 at 12:15:00ID: 17227105

what do you get if you put in this for your URL:

http://localhost/sandpit/JSRS/MultiDropDownXMLHttp2.php

If you don't get any output be sure to check your PHP error log on your web server.

Neal.

 

by: ellandrdPosted on 2006-08-01 at 12:20:17ID: 17227164

i get nothing...

 

by: ellandrdPosted on 2006-08-01 at 12:25:21ID: 17227212

in my logs i get this:

Fatal error:  Uncaught exception 'com_exception' with message '<b>Source:</b> Microsoft JET Database Engine<br/><b>Description:</b> Could not find file 'W:\\db.mdb'.' in W:\\Apache\\htdocs\\sandpit\\JSRS\\MultiDropDownXMLHttp2.php:32\nStack trace:\n#0 W:\\Apache\\htdocs\\sandpit\\JSRS\\MultiDropDownXMLHttp2.php(32): com->open('Provider=Micros...')\n#1 {main}\n  thrown in W:\\Apache\\htdocs\\sandpit\\JSRS\\MultiDropDownXMLHttp2.php on line 32, referer: http://localhost/sandpit/JSRS/


I though so - its my database...

see  - this is a problem for me as i dont understand that way you connect to the access database.

i usually connect like this:

function db_connect()
{
   $link_id = odbc_connect('MY_DSN_NAME');
    return $link_id;
}

$link_id = db_connect();

$query = 'SELECT ....';
$result = odbc_exec($link_id, $query);

then i do either this:

while($row = odbc_fetch_array($result))
{
    echo $row['MY_FIELD_NAME'];
}

or this:

$fieldname = odbc_result($results,'MY_FIELD_NAME');

.

Sorry but the way you coded the connecting is confusing me to what i already know....

anyways, we know the path the DB is wrong hence why my selectboxes are blank...

 

by: nschaferPosted on 2006-08-01 at 12:28:27ID: 17227244

>> also what would this be in PHP:

Sorry I thought I had taken out all of the asp.  I missed a spot though.  As the note in it says this is not really important as it simply displays the results, normally you would be using php here to save the data or process it however you needed.  I'll translate this below:
----------------------------------------------------------------
ASP Code
----------------------------------------------------------------
<%
' This section is just to display the results. Normally you
' would submit to another page, or have this page save the
' results to a database.

if request.form("yr") > "" then
response.write("<b>You Selected: </b><br />")
response.write("Year: " & request.form("yr") & "<br />")
response.write("Make: " & request.form("mk") & "<br />")
response.write("Model: " & request.form("mod") & "<br />")
response.write("Engine: " & request.form("style") & "<br />")
response.write("<input type=button value='Close Window' onclick='window.close();' />")
response.end
end if
%>

------------------------------------------------------------
php code
------------------------------------------------------------
<?php
/*
This section is just to display the results. Normally you
would submit to another page, or have this page save the
results to a database.
*/

if (! $_Post["yr"] == "") {
  echo "<b>You Selected: </b><br />";
  echo "Year: " . $_Post["yr"] .  "<br />";
  echo "Make: " . $_Post["mk"] . "<br />";
  echo "Model: " . $_Post["mod"] . "<br />";
  echo "Engine: " . $_Post["style"] . "<br />";
  echo "<input type=button value='Close Window' onclick='window.close();' />";
  die();
}
?>
-----------------------------------------------

I think the above code should work.  I'm not too sure if the die() command is the same as response.end.  Response.End in asp will stop the processing of the script at that point.

Neal.

 

by: ellandrdPosted on 2006-08-01 at 12:46:10ID: 17227433

still no luck...

can you upload the files somewhere?

 

by: nschaferPosted on 2006-08-01 at 12:55:04ID: 17227524

ellandrd,

>> Sorry but the way you coded the connecting is confusing me to what i already know....
That's ok.  As I stated earlier, PHP is not my primary langauge, so the way I am accessing the DB may be not the best way, or at least unusual by PHP standards.  

If you have a DSN setup for your database and want to use that method, that is fine.  I'll explain the code I've included in any case.

Here's the code I used for connecting to the database:
----------------------------------------------------------------
$db = new COM("ADODB.Connection");
$datapath= substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'],'\\')) . "\db.mdb";
$ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" . $datapath;
$db->open($ConnStr);
-------------------------------------------------------------------

Let's look at it line by line
=====
$db - new COM("ADODB.Connection");
  - This line creates an ADODB Connection.  That means it creates a connection object.  Calls to the db will be made through the connection object.  This does not open the connection, it simply creates the object to hold the connection.
=====

$datapath= substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER'SCRIPT_FILENAME'],'\\')) . "\db.mdb";
  - This is getting the path to the databse file.  This is assuming that the mdb file is in the same path as the script that is calling it.  (Not the safest way to go, but for demo puposes it will do).  Here's how it breaks down.  $_SERVER['SCRIPT_FILENAME] returns the path and filename of the script that is calling it.  In yourcase it will return:
    W:\Apache\htdocs\sandpit\JSRS\MultiDropDownXMLHttp2.php

strrpos($_SERVER['SCRIPT_FILENAME'],'\\') returns the position of the last backslash in the file path.

We use the substr() function to take all the characters up to the last backslash.  This gives us in your case:
    W:\Apache\htdocs\sandpit\JSRS

Now we add "\db.mdb" to it and get the full path to the database file
    W:\Apache\htdocs\sandpit\JSRS\db.mdb

If you wanted to you could simply put in
  $datapath = "W:\Apache\htdocs\sandpit\JSRS\db.mdb";

This line simply makes the code more portable.
=====

$ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" . $datapath;

This simply creates a string that includes the type of database and the path to the data file.  This will be used to open the connection in the next line.
=====

$db->open($ConnStr);

This actually opens the connection to the database.  Now we have communications to the database and can run querys against it.  
--------------------------------------------------------------------

So lets say we want to get a recordset containing all of the records in the table tbCars.  We could do it like this.

$sql = "Select * from tbCars";
$rs = $db->execute($sql);

This will create a recordset called $rs which we can use to view the data.



Hope this helps,

Neal




 

by: ellandrdPosted on 2006-08-01 at 13:02:47ID: 17227601

ive tried again with your code and still cant connect...  path is not correct...

 

by: nschaferPosted on 2006-08-01 at 13:15:51ID: 17227757

OK,  Here's a working example with a zipped copy of the db and two php files.

http://www.applicationgroup.com/tutorials/MultiDropDownXMLHttp1.php

Neal.

 

by: nschaferPosted on 2006-08-01 at 13:17:26ID: 17227777

Note, I found a problem in one of my earlier conversion from asp to php.  Where I used $_Post should read $_POST.  This correction is already made example I just posted.

Neal.

 

by: ellandrdPosted on 2006-08-01 at 13:24:03ID: 17227856

see this line:

var sURL = "MultiDropDownXMLHttp2.asp";

is this correct? should it not be .php ?

 

by: ellandrdPosted on 2006-08-01 at 13:27:16ID: 17227891

ok ive just extracted the 3 files into:

w:\apache\sandpit\neal\

and tried to run:

http://localhost/sandpit/neal/MultiDropDownXMLHTTP1.php

and the selectboxes are still blank?

do i have to enable something for AJAX or XMLHTTP to work?  im using FF, IE6 and 7

 

by: nschaferPosted on 2006-08-01 at 14:17:50ID: 17228413

I don't use apache, so I don't know if there is anything you need to do there.  The fact that you were getting error messages in your php error log makes me think that things are probably set up ok.

is this correct? should it not be .php ?
  Yes it should.  I can't believe I didn't change that in my example after pointing it out above.  I've corrected it in my example and the zip file.  The line now reads:
  var sURL = "MultiDropDownXMLHttp2.php";

After fixing that I found another problem.  The logic I was using to determine which drop-down needed to be filled in did not work in PHP.  I have corrected this and updated the zip file on the tutorial.  This can be found here:

http://www.applicationgroup.com/tutorials/MultiDropDownXMLHttp1.php

Sorry about the problems and frustrations this may have caused you

Neal.

 

by: ellandrdPosted on 2006-08-02 at 00:31:59ID: 17230947

ok ive just tried it on a windows server and it works perfect... i think it wasnt working for me as im using apache server and i thinking ADODB.Conncetion dont work on Apache... itsnt is just a ASP or IIS conection method??

Anyways, ive got it working on a Windows server, so now i going to  change the connection method to use DSN.

When i have it working, i will post the code heres o you can add it to your website tutorial for users on Apache/Linux/Unix server...

 

by: ljubiccicaPosted on 2006-08-02 at 00:47:20ID: 17231004

the way i connect (php any mysql)

function connect(){
$host = "localhost";   //probably localhost
$user = "root";
$pass = "";              //your pass
$db = "";                //database
mysql_connect($host, $user, $pass);
mysql_select_db($db);
}

//after that you just call

connect();

//hope this helps...
=)
Ljubiccica

 

by: _Maddog_Posted on 2006-08-02 at 00:54:30ID: 17231020

Ellandrd,

I'm very happy that you've got help and not giving up anymore :)
The first step is the most important one.

Keep on with the good work.

- Maddog

 

by: ellandrdPosted on 2006-08-02 at 00:57:31ID: 17231032

ljubiccica

Yes but the way Neal connects is different to what i know:

http://www.experts-exchange.com/Web/Web_Languages/PHP/Q_21940220.html

 

by: ellandrdPosted on 2006-08-02 at 05:28:59ID: 17232586

Neal,

Can i See your connection code in your dataopen2.asp file please?

 

by: nschaferPosted on 2006-08-02 at 09:22:13ID: 17234794

ellandrd,

I don't actually have that file any longer.  The data code for this script was moved into the script itself and I guess I didn't update the "Show Source Code" page to reflect that.  The code is exactly what has been posted above.

It is possible that my connection techniques do not work with Apache.  Never having used Apache I don't know.  As I stated earlier though, so long as you can get to the data it doesn't matter to the script how you make the connection.  The Query Strings and general logic will remain the same.

Looking at your normal connection string you listed above:
----------------------------------------
function db_connect()
{
   $link_id = odbc_connect('MY_DSN_NAME');
    return $link_id;
}
$link_id = db_connect();
$query = 'SELECT ....';
$result = odbc_exec($link_id, $query);

then i do either this:
while($row = odbc_fetch_array($result))
{
    echo $row['MY_FIELD_NAME'];
}
or this:
$fieldname = odbc_result($results,'MY_FIELD_NAME');
-------------------


You could run the code like this:
-----------------------------------------------
<?php
/* ------------------ */
/*  Create SQL Query  */
/* ------------------ */

if (empty($_GET["year"])) {
  $sql = "Select distinct [year] From tbCars Order by Year";
}
elseif (empty($_GET["make"])) {
  $sql = "Select distinct Make From tbCars" .
         " Where year = " . $_GET["year"] .
         " Order by Make";
}        
elseif (empty($_GET["model"])) {
  $sql = "Select distinct Model From tbCars" .
         " Where year = " . $_GET["year"] .
         "   and make = '" . $_GET["make"] . "'" .
         " Order by model";
}        
else {
  $sql = "Select distinct Engine From tbCars" .
         " Where year = " . $_GET["year"] .
         "   and make = '" . $_GET["make"] . "'" .
         "   and model = '" .$_GET["model"] . "'" .
         " Order by engine";
}

/* --------------- */
/*  Open Database  */
/* --------------- */
function db_connect()
{
   $link_id = odbc_connect('MY_DSN_NAME');
    return $link_id;
}
$link_id = db_connect();

then i do either this:

/* --------------- */
/*   Get Records   */
/* --------------- */
$result = odbc_exec($link_id, $sql);
$output = "";

while($row = odbc_fetch_array($result))
{
  if (!$output == "") $output = $output . ",";
  $output = $output . $row[0];
}

/* ------------------ */
/*   Display Output   */
/* ------------------ */
echo $output;
?>

I can't test this because I don't have Apache setup, but give it a try and let me know.

Neal.



 

by: ellandrdPosted on 2006-08-03 at 03:11:12ID: 17240321

OK, i have got my code working using your example.

since i was having issues with both versions, i managed to get it working after 2 days..

the code i managed to get working was this:

<?php
include('../includes/db.inc.php');
$link_id = db_connect();

if(empty($_GET["location"]))
{
        $query = "SELECT DISTINCT(location) FROM tblJobs";
      $result = odbc_exec($link_id,$query) or die(odbc_errormsg());

      $locations = array();

      while($row = odbc_fetch_array($result))
      {
            $locations[] = $row['location'];
      }
      
      foreach ($locations as $location)
            $parsedLocation .= $location.',';

      $parsedLocation = substr($parsedLocation,0,-1);

      echo $parsedLocation;
}
else if(empty($_GET["title"]))
{
        $query = "SELECT DISTINCT(title) FROM tblJobs WHERE location = '".$_GET["location"]."'";
      $result = odbc_exec($link_id,$query) or die(odbc_errormsg());

      $titles = array();

      while($row = odbc_fetch_array($result))
      {
            $titles[] = $row['title'];
      }
      
      foreach ($titles as $title)
            $parsedTitle .= $title.',';

      $parsedTitle = substr($parsedTitle,0,-1);

      echo $parsedTitle;
}
else
{
        $query = "SELECT DISTINCT(jobtype) FROM tblJobs WHERE location = '".$_GET["location"]."' AND title = '".$_GET["title"]."'";
      $result = odbc_exec($link_id,$query) or die(odbc_errormsg());

      $jobtypes = array();

      while($row = odbc_fetch_array($result))
      {
            $jobtypes[] = $row['jobtype'];
      }
      
      foreach ($jobtypes as $jobtype)
            $parsedJobType .= $jobtype.',';

      $parsedJobType = substr($parsedJobType,0,-1);

      echo $parsedJobType;
}
?>

I know its long and reduntant but its the only code i could get working.. might be useful to rise this issue on your tutorials...

I will show you our live website using your dropdown example (credit/copyright going to Neal Schfer (nschfer)) later today....

thank you

 

by: nschaferPosted on 2006-08-03 at 09:29:19ID: 17243126

ellandrd,

I happy that it is working.  If you'd like to post the code to your db.inc.php file (changing any confidential data to xxxx or something like that) I'd be pleased to include it with the tutorial as a method to have the script work with Apache of course giving you credit for the code.

Neal.

 

by: ellandrdPosted on 2006-08-03 at 09:30:42ID: 17243137

<?php
function db_connect()
{
      $link_id = @odbc_connect('my_dsn_name_here','','') or die('FATAL ERROR: Could not contact the database server!');      
      return $link_id;
}
?>

 

by: nschaferPosted on 2006-08-03 at 09:33:14ID: 17243164

Thanks,

Neal.

 

by: ellandrdPosted on 2006-08-03 at 09:36:23ID: 17243202

p.s this is the notice i have in the page that ive used your code:

The Dynamic Filtering Select Boxes seen on this browse page is Copyright of Neal Schfer.
All credit going to Neal's hard work at developing such a tool.  Learn more at http://www.applicationgroup.com/tutorials/

This is OK?

 

by: nschaferPosted on 2006-08-03 at 15:22:38ID: 17246058

That is ok, but not necessary.  Put it in if you like, but I certainly haven't copyrighted the code nor do I have any intention of doing so.

Neal.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...