Page 1 of 1

Ordering the if statements

Posted: Thu Aug 06, 2009 5:15 am
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);    
        }
 
    }

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 6:27 am
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'] ?

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 6:33 am
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.

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 8:11 am
by papa
No worries, good advice!

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 8:37 am
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.

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 9:01 am
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.

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 11:55 am
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.

Re: Ordering the if statements

Posted: Thu Aug 06, 2009 12:37 pm
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>';
    }
}

Re: Ordering the if statements

Posted: Fri Aug 07, 2009 8:29 am
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.

Re: Ordering the if statements

Posted: Fri Aug 07, 2009 3:12 pm
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

Re: Ordering the if statements

Posted: Fri Aug 07, 2009 11:09 pm
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.