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 :)
Peter KromanSales ExecutiveAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Chris StanyonWebDevCommented:
Hey Peter,

You would need to move your if statement to be outside of the 'success' block:

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

Open in new window

Maybe a cleaner solution would be to process your form earlier on, and create an $errors array:

<?php
$errors = [];
if (empty($_POST['to'])) $errors[] = "Du har ikke udfyldt 'Til'";
if (empty($_POST['subject'])) $errors[] = "Du har ikke udfyldt 'Emne'";
if (empty($_POST['message'])) $errors[] = "Du har ikke skrevet en besked";
?>

Open in new window


And then in your HTML part:

<?php if ( count($errors) ): ?>

    <div class="mailmessage error">
        <?php foreach ($errors as $error):
            echo $error;
        endforeach; ?>
    </div>

<?php else: ?>

    <div class="mailmessage success">
        Din mail er sendt til <?= $_POST['to'] ?>
    </div>

<?php endif; ?>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Julian HansenCommented:
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.
0
Peter KromanSales ExecutiveAuthor Commented:
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 :)
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Peter KromanSales ExecutiveAuthor Commented:
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?
0
Chris StanyonWebDevCommented:
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 :)
0
Peter KromanSales ExecutiveAuthor Commented:
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 ?
0
Chris StanyonWebDevCommented:
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.
0
Peter KromanSales ExecutiveAuthor Commented:
Thanks Chris :)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
HTML

From novice to tech pro — start learning today.