Ordering the if statements

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
onthespot
Forum Newbie
Posts: 1
Joined: Thu Aug 06, 2009 5:12 am

Ordering the if statements

Post by onthespot »

Hey guys, i'm new to this board, so sorry if this is the wrong place to post the question.
My problem is that I have a bunch of IF statements I just can't get in the correct order.
I have tried several different combinations that I think make sense.

The order intends to go through all the if statements and then if they all pass, finally execute the mysql query.

If you could help, I would really appreciate it, thankyou

Code: Select all

    if (!empty($_POST))
    {
 
        if(!$subject || strlen($subject = trim($subject)) == 0)
            echo "Subject not entered";
        else if(!$comment || strlen($comment = trim($comment)) == 0)
            echo "Comment not entered";
        else if(!$comment || strlen($comment = trim($comment)) < 10)
            echo "Comment too short, must be 10 characters at least";
        else if (isset ($_FILES['new_image']))
                {
                    
                    $imagename = $subject . '.jpg';
                    $source = $_FILES['new_image']['tmp_name'];
                    $target = "images/news/".$imagename;
                    $file = explode('.', $source);
                    $ext = end($file);
                    move_uploaded_file($source, $target);
                    
                    $imagepath = $imagename;
                    $save = "images/news/" . $imagepath; //This is the new file you saving
                    $file = "images/news/" . $imagepath; //This is the original file
 
                    list($width, $height) = getimagesize($file) ;
 
                    $modwidth = 150;
 
                    $diff = $width / $modwidth;
 
                    $modheight = $height / $diff;
                    $tn = imagecreatetruecolor($modwidth, $modheight) ;
                    $image = imagecreatefromjpeg($file) ;
                    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
 
                    imagejpeg($tn, $save, 100) ;
 
                    $save = "images/news/sml_" . $imagepath; //This is the new file you saving
                    $file = "images/news/" . $imagepath; //This is the original file
 
                    list($width, $height) = getimagesize($file) ;
 
                    $modwidth = 80;
 
                    $diff = $width / $modwidth;
 
                    $modheight = $height / $diff;
                    $tn = imagecreatetruecolor($modwidth, $modheight) ;
                    $image = imagecreatefromjpeg($file) ;
                    imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
 
                    imagejpeg($tn, $save, 100) ;
                
            
                }
                
        else if ($ext !== 'jpg' || $ext !== 'jpeg')
                    echo 'Your file must be a jpeg';
 
        else if (!$comment || strlen($comment = trim($comment)) > 10)
        {
            echo "".$_SESSION['username'].", you have added a news piece";
            mysql_query($query);    
        }
 
    }
Last edited by Benjamin on Thu Aug 06, 2009 6:29 am, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Ordering the if statements

Post by papa »

After a quick look I wonder.

You can shorten your statements a little bit:

Code: Select all

 
if(empty($subject)) echo "Subject not entered";
 
I also wonder if you don't mean $_POST['subject'] ?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Ordering the if statements

Post by Benjamin »

Your algorithm is flawed and not workable. I would use a try/catch block...

Code: Select all

 
try {
    if (!$subject || strlen($subject = trim($subject)) == 0) {
        throw new Exception("Subject not entered");
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
 
Also,

Code: Select all

!$subject || strlen($subject = trim($subject)
is the same as

Code: Select all

empty($subject);
See:
Exceptions

EDIT: Sorry papa didn't see your post.
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: Ordering the if statements

Post by papa »

No worries, good advice!
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Re: Ordering the if statements

Post by VladSun »

astions wrote:Your algorithm is flawed and not workable. I would use a try/catch block...
Personally, I'd never advice somebody to use Exceptions when a simple error message(s) could be returned.
I think Exceptions are evil :)
astions wrote:

Code: Select all

!$subject || strlen($subject = trim($subject)
is the same as

Code: Select all

empty($subject);
No, it's not the same:

http://us3.php.net/manual/en/function.empty.php
he following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

Code: Select all

$subject = "    ";
 
if (empty($subject))
    echo "Empty.";
    
if (!$subject || strlen($subject = trim($subject)) == 0)
    echo "Not empty, but only white spaces.";
Ouput

Code: Select all

Not empty, but only white spaces.
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Ordering the if statements

Post by superdezign »

I'd suggest you format your input prior to validation rather than during.

Code: Select all

if (!empty($_POST)) {
    foreach ($_POST as $key => $value) {
        $_POST[$key] = trim($value);
    }
    
    if (empty($_POST['subject'])) {
        ...
    } else if (empty($_POST['comment'])) {
        ...
    } else if (strlen($_POST['comment']) < 10) {
        ...
    } else {
        ...
    }
}
As a side note, the file extension does not determine the file type. Look into PHP GD for image verification.
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Ordering the if statements

Post by peterjwest »

I agree with superdezign, but I'd go one step further:

Code: Select all

 
if (!empty($_POST)) {
    //filtering
    foreach ($_POST as $key => $value) {
        $_POST[$key] = trim($value);
    }
   
   //validation
   $invalid = false;
   $errorMessage = null;
    if (empty($_POST['subject'])) {
      $invalid = true;
      $errorMessage .= 'subject not entered, ';
    }
    if (strlen($_POST['comment']) < 10) {
      $invalid = true;
      $errorMessage .= 'comment must be at least 10 characters, ';
    }
    
    //execution
    if ($invalid) {
      echo ucfirst(substr($errorMessage,0,-2));
    }
    else {
        //do the stuff!
    }
}
 
This way you get an error message containing all the errors, you can also add or remove validation checks easily. Your validation is now separated from your execution so you can add code between the two sections or extract either of the sections into a function or object, basically its more maintainable.

Also 'comment must be at least 10 characters' catches empty comments too so you don't need that separately, unless you want to.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Ordering the if statements

Post by superdezign »

Even better, use an array. I made my own form building and validating framework that I'm still using (though it is still beta do to little nuances like inconsistencies with dealing with checkboxes) and the Form object has an array of error messages and the form elements that they belong to, and those Form_Element objects each have an array of the error messages that belong to them. This way, errors are displayed as a list at the start of the form and shown with the element that the error belongs to.

Code: Select all

 
if (!empty($_POST)) {
    $errors = array();
 
    // Error checking goes here...
 
    $errorDisplay = '';
    if (!empty($errors)) {
        $errorDisplay = '<ul class="errors"><li>'
                      . implode('</li><li>', $errors)
                      . '</li></ul>';
    }
}
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Ordering the if statements

Post by peterjwest »

That's a nice idea, although you might benefit from creating an error class which has an instance in each Form object/element. This means if the implementation of how you deal with validation changes then you don't have to change anything in the Form class. It also makes it easier to include error messages in other classes. Although this is probably not useful/relevant for onthespot.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Re: Ordering the if statements

Post by superdezign »

peterjwest wrote:Although this is probably not useful/relevant for onthespot.
Hehe, we do have a tendency to go overboard, don't we? :3
peterjwest
Forum Commoner
Posts: 63
Joined: Tue Aug 04, 2009 1:06 pm

Re: Ordering the if statements

Post by peterjwest »

I think off-topic is ok when the initial problem has been solved. This thread will soon disappear into the endless catacombs which are internet forums.
Post Reply