Jump to content

simple if empty query fails


wmguk

Recommended Posts

Hey this is my code, Im trying to get it so that if the variable test is empty then set it as 1, however if its not empty then use the field....

 

<? if (empty($_POST['test'])) { $test = '1'; } else { $test = $_POST['test']; } echo $test; ?>

 

however for some reason its failing, and displaying 1 all the time....

Link to comment
https://forums.phpfreaks.com/topic/130055-simple-if-empty-query-fails/
Share on other sites

that should work...

 

replace that line of code with this little snippet and hopefully you'll see whats going on...

<?php

echo "<p>POST['test'] = " . $_POST['test'] . "</p>";

$test = empty($_POST['test']) ? 1 : $_POST['test'];

echo "<p>test = " . $test . "</p>";

?>

that should work...

 

replace that line of code with this little snippet and hopefully you'll see whats going on...

<?php

echo "<p>POST['test'] = " . $_POST['test'] . "</p>";

$test = empty($_POST['test']) ? 1 : $_POST['test'];

echo "<p>test = " . $test . "</p>";

?>

 

Notice: Undefined index: test in /var/www/vhosts/domain.co.uk/httpdocs/school/school.php on line 2

POST['test'] =

test = 1

 

so that is saying that is empty and then it changes it to 1....

 

-----------

 

then on a page where is specifies it as 0

 

POST['test'] = 0

test = 1

 

so even if it is 0 it changes it to 1....

 

is it because 0 is the same as null?

Hey this is my code, Im trying to get it so that if the variable test is empty then set it as 1, however if its not empty then use the field....

 

<? if (empty($_POST['test'])) { $test = '1'; } else { $test = $_POST['test']; } echo $test; ?>

 

however for some reason its failing, and displaying 1 all the time....

 

aside from your horrible habit of not indenting, your code should have worked fine, which means your form is not sending the value to your script.  Post your form.

ah sorry, i've fixed it now, it was the form! I was sending the wrong info!!!

 

Thanks for the pointers!

 

Crayon Violent - which habbit of not indenting?  When I learnt PHP (self taught, still learning) I just started writing, is there guidlines on indenting the script?

 

I normally try

 

<?
//THIS IS WHAT IM DOING

$var = 'abc'
    echo $var ;

if ($var == '123'){
    echo "this text";
} else {
    echo "this instead";
} ?>

 

but im learning so if i should do something else then I'd be happy to do it :)

When a variable contains the value "0" (zero), the empty() function will return TRUE instead of FALSE

 

The following always works:

<?php
$test = (isset($_POST['test']) && (strlen(trim(stripslashes($_POST['test']))) > 0)?$_POST['test'] : 1;
?>

 

Ken

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.