Link to home
Start Free TrialLog in
Avatar of Peter Kroman
Peter KromanFlag for Denmark

asked on

Targetting a HTML element in PHP

Hi,

I am attending a few of the many online PHP education courses right now, and here I have got a little challenge.

I have made this "send e-mail" form, and I am trying to create two message pop-up's to give message if the message is sent or if there is missing something to be filled in the form.
For education purposes I would very much like to make this in PHP, and it here I am getting in trouble.

With the code below, I get the right message with a green background if all fields in the form is filled out before submitting, but when I miss to fill one ore more fields in the form it displays the red background with the right message in it, but the problem is that it also displays the green box - now empty - and places it below the red one.

If anybody can give me a hint how to get the green box to disappear when all fields not are filled I would be very grateful :)

<form class="" action="index.php" method="post" style="width: 150px; margin-left: 8px; "> 
  <h3>Send e-mail</h3>
  <input type="text" name="to" value="" placeholder ="Til"><br><br>
  <input type="text" name="subject" value="" placeholder="Emne"><br><br>
  <textarea rows="10" cols="30" name="message" placeholder="Besked"></textarea><br><br>
  <input type="submit" name="" value="Send besked" style="margin-left: 50px; ">
</form>

<?php
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
?>

<div class="mailmessage" style ="background: #ff3300; color: #fff; font-weight: bold; width: 300px; height: 24px: margin-top: 8px; ">
<?php
if (empty($_POST['to']))
  echo "Du har ikke udfyldt 'Til'";
elseif (empty($_POST['subject']))
  echo "Du har ikke udfyldt 'Emne'";
elseif (empty($_POST['message']))
  echo "Du har ikke skrevet en besked";
else echo "";
?>
</div>

<div class="mailmessage" style ="background: #55ff00; width: 300px; height: 24px;  margin-top: 8px; ">
<?php
  if ((!empty($_POST['to'])) && (!empty($_POST['subject'])) && (!empty($_POST['message'])))
    echo "Din mail er sendt til " .  $_POST['to'];
  else echo "";?>
</div>

Open in new window


            PS! I know I have a little inline styling in the code - but that is because this is only for training. Please don't let that disturb you :)
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Some general pointers
1. Don't put your view code (form) in the same script as your processing code. There are a number of good reasons for this.
a) Tight coupling of your view code and your processing code makes the code difficult to read
b) It makes it difficult if you want to move to an alternative processing solution (such as AJAX)
c) You run the risk of your code not being idempotent. When you post you process then redirect to the view so you can't submit the same page on refresh again.

2. Consider extracting your post variables to safe variables
$to = isset($_POST['to']) ? $_POST['to'] : false;
// Do further sanitisation here.

Open in new window

Now you have a variable that is guaranteed to have a value which you can test and act on instead of (As you have it) multiple empty() tests.

3. This is a personal preference. Use { } on if / else even when there is only one statement. They are not necessary but they accomplish two key things
a) Readability - they show a definite boundary of a code block
b) If you add to the logic down the line you don't end up with weird side effects because your code appears to be running even when a condition says it shouldn't - avoiding side effects is a good practice and worth the extra line you would save if you did not use the { }

4. Avoid using code that does not do anything such as
else echo "";

Open in new window

This is basically saying else do nothing - in which case simply leave the else off.

5. Take some time to understand PHP strings and how to use them so you can make your code more readable specifically with respect to string concatenation (replace with variable embedding and HEREDOC) - more here

5. Consider an AJAX solution. This makes for much simpler code on the backend. You send through the form variables - the backend process validates those and sends back a status and (optionally) a message. Based on the status - you use JavaScript to display the message.
Avatar of Peter Kroman

ASKER

Thanks Chris and Julian,

@Chris - I am working with your "cleaner" solution, and I am getting back later to check with you if I have understood what you are doing inthere :)
Let's see if I have got it right - my understanding added in comments:

<?php
$errors = []; //create an array named 'errors'
if (empty($_POST['to'])) $errors[] = "Du har ikke udfyldt 'Til'";  //if the POST'ed field named 'to' is empty then look in the array named 'errors' index 0 and add the string to the array
if (empty($_POST['subject'])) $errors[] = "Du har ikke udfyldt 'Emne'"; //if the POST'ed field named 'subject' is empty then look in the array named 'errors' index 1 and add the string to the array
if (empty($_POST['message'])) $errors[] = "Du har ikke skrevet en besked"; //if the POST'ed field named 'message' is empty then look in the array named 'errors' index 2 and add the string to the array
?>

Open in new window


<?php if ( count($errors) ): ?> // test if there is data in the array named 'errors' 

    <div class="mailmessage error">
        <?php foreach ($errors as $error): //if data is present in the array, then look for every instance through the array and place it a variable named 'error'
            echo $error; //send the content od the variable 'error' to the page and print it out on the screen
        endforeach; ?>
    </div>

<?php else: ?> // if there is no data in the array named 'errors'

    <div class="mailmessage success">
        Din mail er sendt til <?= $_POST['to'] ?> // send a message to the page that tells the user that the email is sent to the address in the firld named 'to' and print it out on the screen
    </div>

<?php endif; ?>

Open in new window


Hope I have become a little bit more skilled since we talked last :)
One little question is bothering me though:
I can't figure out when to use ?<php endif; ?> and when not tu use it. Is there a good rule for that?
Hey Peter. Nice work. You understand it well :)

Regarding the <?php endif; ?> ... In PHP you can write control blocks (if / foreach / while / for / switch etc) using the curly brackets - {} - or you can use an alternative syntax, for example:

if (someValue) {
    // do something
}

if (someValue):
    // do something
endif;

foreach ($errors as $error) {
    echo $error;
}

foreach ($errors as $error):
    echo $error;
endforeach;

Open in new window

Effectively, they're identical, so which you use is a personal choice of style. Often, I tend to use the curly brackets for short, inline code, so I would use:

if ($value) {
    // lets do something.
}

However, if I'm splitting the start and end of a control block over a larger area, or I'm jumping out of PHP altogether then I tend to use the alternative syntax:

<?php if ($value): ?>

    <p>We're now outside of the PHP script and dealing purely with HTML</p>

<?php endif; ?>

Open in new window

I'll also use this syntax if I'm nesting various control blocks :

while ($someValue == true):

    if ($value):

        foreach($array as $item):

        endforeach;

    endif;

endwhile;

Open in new window

I just prefer that style and think it's more intelligible than:

<?php if ($value) { ?>

    <p>We're now outside of the PHP script and dealing purely with HTML</p>

<?php } ?>

<?php while ($someValue == true) {

    if ($value) {

        foreach($array as $item) {

        }

    }

}
?>

Open in new window

As I say - it's really down to personal choice, but if you find yourself trying to match ending curly brackets with opening curly brackets, or you get some weird errors because you've only got 5 closing brackets when you should have 6, then remember the alternative syntax :)
OK - SO it's the difference - an a personal choice - between two possible syntaxes:

<?php if(---):
.....
else:
....
endif;?>

AND

<?php if(...) {
.....
} else {
.....
}

Right - now I've got that too :)

But you have one statement in your code that I haven't seen before and that I can't find in the php manual
It is this one:
<?= ...

I am aware that the syntax <? can be used as opening tag in stead of <?php - but what is the other one with the = added ?
Hey Peter,

Very simply, <?= is just shorthand for <?php echo, so these 2 statements are identical:

<?= "Hello Peter" ?>

<?php echo "Hello Peter" ?>

Again, it's really a styling issue, and only suitable for a quick open / echo / close situation:

Din mail er sendt til <?= $_POST['to'] ?>
Din mail er sendt til <?php echo $_POST['to'] ?>

Historically (pre PHP 5.4) there was a potential problem with using it, because it was directly tied to a config option called short_open_tag. On a lot of hosts, this was disabled (because a short open PHP tag conflicted with an opening XML tag), and so it just wouldn't work. In later versions of PHP though, the shorthand for echo was detached from the short_open_tag config option and is now always enabled, so even if hosts disable short_open_tags, the shorthand for echo will still work.

Hosts can still disable the short open tags, so while the short echo will work, you can't guarantee that the general <? tag will. Use the full <?php tag!

As long as you don't need to run on PHP <5.4 (and you shouldn't!), then it's fine to use it.
Thanks Chris :)