-1

I am learning PHP and trying to test out some code but it won't work and I can't figure out why. I am trying to make a simple form where:

A)When the page first loads beneath the form it says "You have not written anything yet."

B)If something is written in the form field and submitted then beneath the form it says "Your message has been sent"

C)If nothing is written in the form field but the user hits submit that it says "Error: You didn't write anything".

I can get the first two parts to work but no matter what I do I can't get C to work.

Here is my code:

<?php          
    $oldname = isset($_POST['name']);  
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form Test</title>
    </head>
    <body>

        <form method="POST" action="">
            <label for="name">Your Name:</label>
            <input type="text" name="name" id="name">
            <input type="submit" value="submit">
        </form>

        <?php 

            if ($oldname) {
                if ($_POST['name'] = '') {
                    echo "Error: You didn't write anything";
                }
                else {
                    echo "Your message has been sent";
                }
            } 
            else {
                echo "You have not written anything yet";
            }

        ?>

    </body>
</html>
Niall
  • 87
  • 9
  • 1
    Replace `$_POST['name'] = ''` with `$_POST['name'] === ''` See [the manual on comparison operators](http://php.net/manual/en/language.operators.comparison.php). – Will B. Apr 06 '18 at 02:28

2 Answers2

-1

You wrote an assignment in your if statement:

$_POST['name'] = ''

I think you meant to do a comparison:

$_POST['name'] == ''
csb
  • 674
  • 5
  • 13
-1

You have a typo. You were using assignment operator in the if condition which makes it true all the time so it never enters else condition "Your message has been sent".

I have fixed the code. Take a look at it.

<?php          
    $oldname = isset($_POST['name']);  
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form Test</title>
    </head>
    <body>

        <form method="POST" action="">
            <label for="name">Your Name:</label>
            <input type="text" name="name" id="name">
            <input type="submit" value="submit">
        </form>

        <?php 

            if ($oldname) {
                if ($_POST['name'] == '') {
                    echo "Error: You didn't write anything";
                }
                else {
                    echo "Your message has been sent";
                }
            } 
            else {
                echo "You have not written anything yet";
            }

        ?>

    </body>
</html>
Akansha
  • 132
  • 8