csm232s
csm232s

Reputation: 1660

PHP: Can't set variable when $_REQUEST is blank

I'm having issues with setting a variable either with using $_REQUEST or it's my syntax. When checking $_REQUEST['orderBy'], if it's blank/empty I want to set a default value of 'order_date'. However, when it retrieves and empty $_REQUEST['orderBy'] it just remains empty instead of setting it. I made an ugly fix in the code to resolve the issue later on, but I'm just wondering what I'm doing wrong:

$orderBy = isset($_REQUEST['orderBy']) ? stripslashes($_REQUEST['orderBy']) : 'order_date';

Upvotes: 1

Views: 1481

Answers (1)

cantlin
cantlin

Reputation: 3226

There's nothing syntactically wrong with that, but it will set $orderBy to an empty value if $_REQUEST['orderBy'] is set but empty. Try using empty():

$orderBy = (empty($_REQUEST['orderBy'])) ? 'order_date' : $_REQUEST['orderBy'];

If it still doesn't work, you may be mistakenly setting $_REQUEST['orderBy'] prior to this line. You should try to use the more specific super globals like $_POST and $_GET, both because they make your code clearer and more readable, and because they improve the security of your application.

Upvotes: 4

Related Questions