Solved

PHP Switch Problems

Posted on 2013-01-12
35
277 Views
Last Modified: 2013-01-12
I have a webpage with 5 buttons and one dropdown list.  Depending on which button you click on, the listbox will be populated by that MySQL statement.  The switch doesn't seem to work though.  The listbox is not being populated.  The code.

<?php
//$list = $_GET['case'];
//$case = 'cuisine'; 
$dbc = mysql_connect('','','') 
     or die('Error connecting to MySQL server.'); 
 
mysql_select_db('MyDB'); 

$list['Place']   =  mysql_query("select * from tblRestaurants order by RestName ASC");
$list['Cuisine'] =  mysql_query("select * from tblCuisines order by CuisineName ASC");

foreach($list as $key=>$value){
while ($nt = mysql_fetch_assoc($list[$key]))
     $list_array[$key] = $nt;
}
if(isset($_GET["ajax"]))
{
   switch($_GET['$case']){
       case 'Place':
          echo json_encode($list_array['Place']);
          break;
       case 'Cuisine':
          echo json_encode($list_array['Cuisine']);
          break;
}
   die();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
function displayPlace()
{
    $.getJSON("Saturday.php?ajax=true", function(data) {
        $.each(data, function(index, objRecord) {
            var option=document.createElement("option");
            option.value=objRecord.RestID;
            option.text=objRecord.RestName;
            $("#Doggie").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
        });
    });
 
}

function displayCuisine()
{
    $.getJSON("Saturday.php?ajax=true", function(data) {
        $.each(data, function(index, objRecord) {
            var option=document.createElement("option");
            option.value=objRecord.CuisineID;
            option.text=objRecord.CuisineName;
            $("#Doggie").append('<option value="' + objRecord.CuisineID + '">' + objRecord.CuisineName + '</option>');
        });
    });
 
}
 
    </script>
    <title>SEARCH</title>
</head>
<body>
        <form>
        <button type="button"  onclick="javascript:displayPlace();">Place</button>
        <button type="button"  onclick="javascript:displayCuisine();">Cuisine</button>
        <button type="button"  onclick="javascript:displayCity();"  >City</button>
        <button type="button"  onclick="javascript:displayState();">State</button>
        <button type="button"  onclick="javascript:displayZipCode();">Area</button>
        <br /> 
        
        <select name="Doggie" id="Doggie"></select>
       
        <br /> 
    </form> 
</body> 
</html>

Open in new window

0
Comment
Question by:DS928
  • 16
  • 16
  • 2
  • +1
35 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 38770414
$_GET['case']

what is case?
0
 
LVL 82

Expert Comment

by:Dave Baldwin
ID: 38770422
It looks like your file is named "Saturday.php" and you are passing "ajax=true" as a GET.  Your 'switch' statement is however based on $_GET['$case'] and you are Not passing a name/value pair for 'case'.  In addition, $_GET['$case'] should not have the '$' because that says it's a variable instead of an index name.  Should be $_GET['case'].

It would be normal to split this into two separate files, one HTML and a separate PHP file because you are not using the PHP info directly in the HTML part but only thru the AJAX call.
0
 

Author Comment

by:DS928
ID: 38770426
That is a good question!  I imagine that 'case' or whatever it's called need to be attached to the buttons.  But how.  I am new to this, I've been banging thru this with a hammer!  Help is appreciated. Thank you.
0
 

Author Comment

by:DS928
ID: 38770457
Thank you Dave.  So how would I pass the value to 'case' from the buttons?  I think I do need two pages.  The PHP and the javascript on one and the html on another, otherwise the page will get reloaded? Correct? But still the lingering question, how to pass the value?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770494
Your main page :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Q_27993331.html</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
	// WAIT COMPLETE LOADING OF THE PAGE 
	$(document).ready(function() {
		// ATTACH CLICK EVENT TO ALL BUTTON OF THE CURRENT DOCUMENT
		$("button").click(function() {
			// EACH TIME WE CLICK ON A BUTTON, CALL display FUNCTION
			// HERE this represent THE CLICKED BUTTON 
			display( $(this).val() );
		})
	})

	function display(what)
	{
		// CALL getOnlyJSONOptions.php, NOT THE SAME PAGE, THIS IS A SEPARATE PHP SCRIPT
		$.getJSON("getOnlyJSONOptions.php?ajax=true", { "case" : what }, function(data) {
			// REMOVE ANY PREVIOUS OPTIONS FIRST
			$("#Doggie").empty();
			// LOOP OVER THE OPTIONS DATA, OUR JSON OBJECT
			$.each(data, function(index, objRecord) {
				$("#Doggie").append('<option value="' + objRecord.ID + '">' + objRecord.Name + '</option>');
			});
		});
	}
</script>
</head>
<body>
<form>
    <button type="button" value="Place">Place</button>
    <button type="button" value="Cuisine">Cuisine</button>
    <button type="button" value="State">State</button>
    <button type="button" value="ZipCode">Area</button>
    <br /> 
    <select name="Doggie" id="Doggie"></select>
    <br /> 
</form> 
</body>
</html>

Open in new window

getOnlyJSONOptions.php script :
Test it script putting the following URL in your browser :
http://localhost/path/to/your/application/getOnlyJSONOptions.php?case=Place
or this one :
http://localhost/path/to/your/application/getOnlyJSONOptions.php?case=Cuisine
<?php
	$list_array = array();

	if(isset($_GET['case'])) {
		
		$case = $_GET['case'];
		
		$dbc = mysql_connect('','','') 
		or die('Error connecting to MySQL server.'); 
		
		mysql_select_db('MyDB'); 
		
		switch($case){
			case 'Place':
				$list =  mysql_query("select * from tblRestaurants order by RestName ASC");
				break;
			case 'Cuisine':
				$list =  mysql_query("select * from tblCuisines order by CuisineName ASC");
				break;
		}
	
		foreach($list as $key=>$value) while($nt = mysql_fetch_assoc($list[$key])) $list_array[$key] = $nt;		
	}
	
	 header('Content-type: application/json');
	 json_encode($list_array);
	
?>

Open in new window

0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 38770523
corrected getOnlyJSONOptions.php :
the primary key (id) column of your table is : id
<?php
	$list_array = array();

	if(isset($_GET['case'])) {
		
		$dbc = mysql_connect('', '', '') or die('Error connecting to MySQL server.'); 
		$case = mysql_real_escape_string($_GET['case']);
		
		mysql_select_db('MyDB'); 
		
		switch($case){
			case 'Place':
				$result = mysql_query("select id as ID, RestName as Name from tblRestaurants order by RestName ASC");
				break;
			case 'Cuisine':
				$result = mysql_query("select id as ID, CuisineName as Name from tblCuisines order by CuisineName ASC");
				break;
		}
		if($result)
			while($row = mysql_fetch_assoc($result)) {
				$list_array[] = array("ID"=>$row["ID"], "Name"=>$row["Name"]);		
			}
	}
	
	header('Content-type: application/json');
	echo json_encode($list_array);
	
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38770542
How do you eat an elephant?  One byte at a time!  This will be a lot easier if you deconstruct the issues into separate parts.  You might set the javaScript part aside and just concentrate on getting the PHP/MySQL part to work.  Then you can add the jQuery layer back in later.

When you're debugging PHP scripts, var_dump() is your friend.  It can show you what any variable contains, including arrays and objects.
0
 

Author Comment

by:DS928
ID: 38770556
Thank you, I tried the updated script.  Still not populating the list.

switch($case){
			case 'Place':
				$result = mysql_query("select RestID as ID, RestName as Name from tblRestaurants order by RestName ASC");
				break;
			case 'Cuisine':
				$result = mysql_query("select CuisineID as ID, CuisineName as Name from tblCuisines order by CuisineName ASC");
				break;
		}
		if($result)
			while($row = mysql_fetch_assoc($result)) {
				$list_array[] = array("ID"=>$row["ID"], "Name"=>$row["Name"]);		
			}
	}
	
	header('Content-type: application/json');
	echo json_encode($list_array);
	

Open in new window

0
 

Author Comment

by:DS928
ID: 38770561
Thank you, Ray. I am very new to this.  So debbuging although a great suggestion, is beyond my skill scope at this point.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770575
try your query in a sql editor :
select RestID as ID, RestName as Name from tblRestaurants order by RestName ASC
and
select CuisineID as ID, CuisineName as Name from tblCuisines order by CuisineName ASC

again, again, USE two PHP distinct scripts.
One for your page
One to send back JSON, that will remove a possible issue and let you understand how ajax work. Please confirm you understand that.

If your query work, put the following in your web browser address bar :
http://localhost/path/to/your/application/getOnlyJSONOptions.php?case=Place
or this one :
http://localhost/path/to/your/application/getOnlyJSONOptions.php?case=Cuisine

you MUST see the JSON object in your browser
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38770603
If you find that debugging is out of your reach, consider hiring a professional programmer.  You will save a lot of time and money that way, and you may be able to get the results you need in very quick order.  If you want to learn to do this stuff yourself, get this book for starters.  It has excellent examples and is very readable.  Most importantly it builds the learning experience in a structured way so you will never find yourself in "over your head."
http://www.sitepoint.com/books/phpmysql5/
0
 

Author Comment

by:DS928
ID: 38770625
I ran the queries and the both work.  Cannot see in my Browser.  I have two files, the main one XSAT.php and the getOnlyJSONOptions.PHP...not sure if I understand the two distint scripts.
0
 

Author Comment

by:DS928
ID: 38770632
Thank you Ray.  Nice suggestion.  I will order the books.  In the meantime, I have almost the whole website down except for this problem.  I had it working on one button only, but when I had to add the four buttons that chaged the whole ballgame. You see what we have so far.  What do you suggest needs to be done?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770657
I just want to be sure XSAT.php don't have the code retrieving the options data...
So if getOnlyJSONOptions.php don't show any data, you've an error in...
put the in the beggining of it (in bold) :
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);


an report any error you get.
0
 

Author Comment

by:DS928
ID: 38770678
No Errors reported,  But just to be sure that all is square at this point here are my two pages.  I renamed getOnlyJSONOptions.php to mydoggie.php, just easier.

XSAT.php
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
//$dbc = mysql_connect('','','') 
//     or die('Error connecting to MySQL server.'); 
 
//mysql_select_db('MyDB');
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Doggie.html</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
	// WAIT COMPLETE LOADING OF THE PAGE 
	$(document).ready(function() {
		// ATTACH CLICK EVENT TO ALL BUTTON OF THE CURRENT DOCUMENT
		$("button").click(function() {
			// EACH TIME WE CLICK ON A BUTTON, CALL display FUNCTION
			// HERE this represent THE CLICKED BUTTON 
			display( $(this).val() );
		})
	})

	function display(what)
	{
		// CALL mydoggie.php, NOT THE SAME PAGE, THIS IS A SEPARATE PHP SCRIPT
		$.getJSON("mydoggie.php?ajax=true", { "case" : what }, function(data) {
			// REMOVE ANY PREVIOUS OPTIONS FIRST
			$("#Doggie").empty();
			// LOOP OVER THE OPTIONS DATA, OUR JSON OBJECT
			$.each(data, function(index, objRecord) {
				$("#Doggie").append('<option value="' + objRecord.ID + '">' + objRecord.Name + '</option>');
			});
		});
	}
</script>
</head>
<body>
<form>
    <button type="button" value="place">Place</button>
    <button type="button" value="Cuisine">Cuisine</button>
    <button type="button" value="City">City</button>
    <button type="button" value="State">State</button>
    <button type="button" value="ZipCode">Area</button>
    <br /> 
    <select name="Doggie" id="Doggie"></select>
    <br /> 
</form> 
</body>
</html> 

Open in new window


and mydoggie.php
<?php
	ini_set('display_errors',1);
    error_reporting(E_ALL);
	
	
	$list_array = array();

	if(isset($_GET['case'])) {
		
		$dbc = mysql_connect('', '', '') or die('Error connecting to MySQL server.'); 
		$case = mysql_real_escape_string($_GET['case']);
		
		mysql_select_db('MyHead'); 
		
		switch($case){
			case 'Place':
				$result = mysql_query("select RestID as ID, RestName as Name from tblRestaurants order by RestName ASC");
				break;
			case 'Cuisine':
				$result = mysql_query("select CuisineID as ID, CuisineName as Name from tblCuisines order by CuisineName ASC");
				break;
		}
		if($result)
			while($row = mysql_fetch_assoc($result)) {
				$list_array[] = array("ID"=>$row["ID"], "Name"=>$row["Name"]);		
			}
	}
	
	header('Content-type: application/json');
	echo json_encode($list_array);
	
?>

Open in new window


*** Private data removed - Modalot, EE Community Support Moderator ***
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770691
ask a moderator to edit your php code, currently we can see login and password

your switch have << Place >>
and not << place >>

and you've
<button type="button" value="place">Place</button>
instead :
<button type="button" value="Place">Place</button>

else your script work fine
0
 

Author Comment

by:DS928
ID: 38770696
Since my password is up have you tried it?  I did changes and its still not working.  By the way how do I get in touch with the moderator?  Today is my first day.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 82

Expert Comment

by:leakim971
ID: 38770704
what do you see when you put : http://localhost/path/to/your/application/getOnlyJSONOptions.php?case=Cuisine

in the address bar of your browser?
0
 

Author Comment

by:DS928
ID: 38770718
HTTP Error 404.0 - Not Found

Maybe I am doing it wrong.
The path where the file is located is....
D:\MenuHead\Website\mydoggie.php?case=Cuisine

so I am doing

 http://localhost/D:\MenuHead\Website\mydoggie.php?case=Cuisine
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770726
what is the name of the website folder inside your htdocs?
start your full path from here not starting by your drive...

what do you type to see the default page of your site?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770731
put both files inside htdocs folder and use :
http://localhost/getOnlyJSONOptions.php?case=Cuisine
and let me know what you're seeing
0
 

Author Comment

by:DS928
ID: 38770739
I dont have an htdocs folder.  I have two drives.  A c: drive for programs and a d; drive for my files, and nowhere did I find htdocs.  Where should I make this folder?
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770762
ok, you need a webserver to use Ajax
you can install one for development purpose : http://www.wampserver.com/en/

BUT you should be able to test your mydoggie.php script putting the following in your webbrowser :

D:\MenuHead\Website\mydoggie.php?case=Cuisine

let me know what you're seeing

If you can see the data go to install the wampserver...  or perhaps you're ready to install both scrips on your hosted server? hostedresource.com
0
 

Author Comment

by:DS928
ID: 38770763
I'm using ISS on my computer.  Do I still need to install wamp?  I also made an htdocs folder on my website server and placed the two files into the folder.  The folder is a sub-folder of html.  Also I am on GoDaddy.  They host my website currently.  Whenever I type D:\MenuHead\Website\mydoggie.php?=Cuisine  I get an error that it's not found.  If I type in D:\MenuHead\Website\mydoggie.php it opens in Dreamweaver showing the code.  The pages are both on the server.  Did you try to run XSAT.php page.  Give it a try.  You have the password info.  Let me know if it works for you.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770789
you need a web server able to interpret php script so put the files on your web service
I confirm the scripts run fine with a correct web server
0
 

Author Comment

by:DS928
ID: 38770804
The files are up.  Just view the XSAT.php in your browser and let me know if you get any returned results.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770807
what is the address?
if needed : http://goo.gl/
0
 

Author Comment

by:DS928
ID: 38770850
Mercy!  It's working!  Kinda.  The first problem was a typo in the connect file, my fault!  So it loaded on the place, so I added the other button querys.  Here is what is strange.
Place gives places
Cuisine gives cities
City gives Cities
State gives Areas
Area gives Areas

It's like every other one is working correctly?  The address id www.menuhead.net, still in play around stage yet.  Also it's very slow.  I thought Ajax was faaasssst. There aren't that many records in there as you can see,

Here's the code.

<?php
	ini_set('display_errors',1);
    error_reporting(E_ALL);
	
	
	$list_array = array();

	if(isset($_GET['case'])) {
		
		$dbc = mysql_connect('','','') or die('Error connecting to MySQL server.'); 
		$case = mysql_real_escape_string($_GET['case']);
		
		mysql_select_db('MyDB'); 
		
		switch($case){
			case 'Place':
			$result = mysql_query("select RestID as ID, RestName as Name from tblRestaurants order by RestName ASC");
			break;
			case 'Cuisine':
			$result = mysql_query("select CuisineID as ID, CuisineName as Name from tblCuisines order by CuisineName ASC");
			case 'City':
			$result = mysql_query("select CityID as ID, CityName as Name from tblCities order by CityName ASC");
			break;
			case 'State':
			$result = mysql_query("select StateID as ID, StateName as Name from tblStates order by StateName ASC");
			case 'Area':
			$result = mysql_query("select AreaID as ID, AreaName as Name from tblAreas order by AreaName ASC");
			break;
		}
		if($result)
			while($row = mysql_fetch_assoc($result)) {
				$list_array[] = array("ID"=>$row["ID"], "Name"=>$row["Name"]);		
			}
	}
	
	header('Content-type: application/json');
	echo json_encode($list_array);
	
?>

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770859
great!
there's no problem inside the XSAT.php page

in mydoggie.php you forget to place a << break; >> after line 20 and after line 25
0
 

Author Comment

by:DS928
ID: 38770872
That did it!  This ended a week of torture!  Thank you so very much!  I appreciate your patience and bedside manor!  Have a good day.
0
 

Author Comment

by:DS928
ID: 38770890
I've requested that this question be closed as follows:

Accepted answer: 0 points for DS928's comment #a38770872

for the following reason:

Knowledgable and patient.  Took the time to do it right along with informative examples,  Did not bash or belittle me for not knowing.  A saint!
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770891
points not awarded correctly
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38770984
you need to choose one of my post to close the question to award points not one of your
0
 

Author Closing Comment

by:DS928
ID: 38771125
Like i said before, the best!  Patient, knowledgable and a great bedside manor!  Really an expert!
0
 
LVL 82

Expert Comment

by:leakim971
ID: 38771128
thanks for your kind words!
have a nice sunday!
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now