Stopping negative numbers

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
megaming
Forum Commoner
Posts: 27
Joined: Wed Dec 25, 2002 12:31 pm

Stopping negative numbers

Post by megaming »

Hi,

How do I stop users sending negative numbers to my database from a form?

I don't want to do this with javascript because that can easily be turned off.

Thanks :D
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You can do a test on the form processing page that checks to see if a number is greater than zero:

Code: Select all

if ($_POST['number'] >= 0){
   echo 'Positive Number';
} else {
   echo 'Negative Number';
}
Mac
megaming
Forum Commoner
Posts: 27
Joined: Wed Dec 25, 2002 12:31 pm

Post by megaming »

I've already got that, but it doesn't work...

Code: Select all

if ($newgold < "0") &#123;
print "You do not have that much!";
&#125;
if ($newgold > "0") &#123;
// do db stuff
&#125;
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Have you tried something like:

Code: Select all

if ($_POST['newgold'] < 0) {
    echo 'You do not have that much!'; 
} else { 
    // do db stuff 
}
Mac
megaming
Forum Commoner
Posts: 27
Joined: Wed Dec 25, 2002 12:31 pm

Post by megaming »

is there actually any difference?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Yes - first of all it uses the $_POST array to reference the variable just in case the problem is one caused by register_globals:
viewtopic.php?t=511

Secondly instead of using two if statements it uses one if...else statement which makes more sense as you can first test if the variable is less than 0 (ie. negative) and then if it's not the default stuff in the else statement is done.

Mac
Post Reply