Jump to content

[SOLVED] Function not working - can someone please look at code and tell me what's wrong?


ShootingBlanks

Recommended Posts

Hello.  The point of what I'm doing in the code below is to have it so that when a user clicks a link, the $_GET['orderType'] variable in the URL will alternate between "ASC" and "DESC" everytime the link is clicked, and the page will reload.  If there is no "orderType" in the $_GET array upon entering the page, then it should default to "ASC".  Here is the code, and below it is the error that I get:

if (isset($_GET['orderType'])) {
switch($_GET['orderType']) {
	case "ASC":
		$orderType = "ASC";
		break;
	case "DESC":
		$orderType = "DESC";
		break;
	default:
		$orderType = "ASC";
}
} else {
$orderType = "ASC";
}

function switchOrder() {
if ($orderType == "ASC") {
	$returnOrder = "DESC";
} else {
	$returnOrder = "DESC";
}
return $returnOrder;
}

 

THEN IN THE BODY OF THE PAGE:

<a href="index.php?orderBy=leader&orderType="<?php echo switchOrder(); ?>>Leader</a>

 

Here is the error that I'm getting (the error is posted within the "Leader" link itself):

 

Notice: Undefined variable: orderType in C:\htdocs\_PHP-SITES\ProjectBoard\index.php on line 125

DESC>Leader

 

Line 125 in my code is the line just under "function switchOrder() {".  Any ideas???  Thanks!

 

The variable $orderType is not global in scope, either pass it into your function or declare it as a global in your function. The former method is preferred.

 

Ken

 

How would I pass it to my function, based on the switch/case statement above the function?  Like, I need it to be declared first in the switch/case statement, so then AFTER that, how do I get that into the "switchOrder" function?  I guess I need to know how to reference a variable inside a function that is located outside of the function beforehand.  I hope what I'm asking made sense.  If not, it's just because I'm new at this!  ;)

 

Okay - I changed the "switchOrder" function to this:

function switchOrder($orderType) {
if ($orderType == "ASC") {
	$returnOrder = "DESC";
} else {
	$returnOrder = "ASC";
}
return $returnOrder;
}

 

And then I amended my link's code to this:

<a href="index.php?orderBy=leader&orderType="<?php echo switchOrder($orderType); ?>>Leader</a>

 

That got rid of any errors, but now my URL reads this anytime it's clicked:

 

/index.php?orderBy=leader&orderType=

 

So, the "orderType" is not being added to the URL.  Am I doing that "return" stuff wrong or something???

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.