0

I am trying to set a variable value if a form is not submitted (where the value comes from). Below I have:

if (empty($order)) { 
   $order = 'ORDER BY product_name DESC'; 
} 

else { $order=$_POST['order']; }

This always sets the value to 'ORDER BY product_name DESC' and ignores the form. Likely just a small issue but I can't pick it out.

Any ideas?

Thank you!

3
  • $order is clearly always empty. Are you sure it is being set before you try to use it? Aslo, your code is insecure as it is wide open to sql injections. Commented Nov 27, 2013 at 17:17
  • 3
    Lovely SQL injection attack vulnerability... Commented Nov 27, 2013 at 17:17
  • 1
    Use prepared statements to shield your application against SQL injections.. Commented Jan 23, 2014 at 19:40

6 Answers 6

1
$order = isset($_POST['order']) ? $_POST['order'] : 'ORDER BY product_name DESC';
Sign up to request clarification or add additional context in comments.

Comments

0

use isset

if (isset($order) && empty($order)) { 
    $order = 'ORDER BY product_name DESC'; 
}else { 
    $order=$_POST['order']; 
}

Comments

0

This happens because $order is always empty. So go and figure out why $order never gets set or has a value of null or empty string. Or use isset($order).

Comments

0

Try using isset :

if (isset($_POST['order'])) { 
$order = 'ORDER BY product_name DESC'; 
} else { 
$order=$_POST['order']; 
}

Comments

0

The variable $order is not set before the if statement. Therefore empty($order) will always evaluate to true. I think you were looking more for the following:

if(empty($_POST['order'])) {
    $order = 'ORDER BY product_name DESC';
} else {
    $order = $_POST['order'];
}

Comments

0

You're checking of $order is empty or set, when you want to check if $_POST['order'] has a value. You should however not use the value submitted directly, but at least validate that it's something you expect it to be. Otherwise you'll make your application open for SQL injection.

$order = false;

if (empty($_POST['order']))
{
    // validate if $_POST['order'] has a valid value and set $order
}

if (!$order)
{
    // set a default order instead, as there either wasn't a POST-value or an invalid value.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.