Problems using is_int in if statement

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
mayajewe
Forum Newbie
Posts: 13
Joined: Sun Feb 01, 2009 12:56 pm

Problems using is_int in if statement

Post by mayajewe »

Hi everyone,

I am using variables in my url with the $_GET statement which I put into a sql statement to retrieve page content from mySQL db. I wanted to prevent sql injection and I thought that as the variable will only contain numbers I could use this as my check. (If it is not a number reset the variable to the default page.)

This is my code below but it doesn't seem to work. I am not sure what I am doing wrong. The outer 'if' statement works but the inner one doesn't, it always evaluates to TRUE even with a valid number. Can anyone help? Thanks,

Code: Select all

 
    $myID = $_GET['contentid'];
    if(empty($myID)){
                echo ("The variable is empty.");
        $myID = 1;
    } else {
        echo ("The variable is not empty.");
        if(!(is_int($myID))) 
            echo ($myID);
            $myID = 1;
    }
 
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Problems using is_int in if statement

Post by Mark Baker »

Values from an HTML form are always strings, even if they contain a numeric value, because the HTML form has no concept of number
Try using is_numeric instead, but watch out for values like "29 Days" which will return true for is_numeric. Most people will use a regexp to validate numeric values for this reason
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Re: Problems using is_int in if statement

Post by s.dot »

Use is_numeric() for the check and then type cast to integer before inserting into the database
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
mayajewe
Forum Newbie
Posts: 13
Joined: Sun Feb 01, 2009 12:56 pm

Re: Problems using is_int in if statement

Post by mayajewe »

Thank you both,

I am now using is_numeric() and after a slight amendment to my if statement it works. :)
Post Reply