Notice: Undefined variable: name in C:\AppServ\www\ContactUs.php on line 217 [duplicate]

StackOverflow https://stackoverflow.com/questions/21910643

  •  14-10-2022
  •  | 
  •  

Question

I make contact us form which show error when field empty

The problem is that I try to make it when fill some field and other not, the error show in empty field and filled field still have their data.

& every time I get this error:

Notice: Undefined variable: name in C:\AppServ\www\ContactUs.php on line 217

This is my code:

<?php
            if (!empty($_POST['action']) && $_POST['action'] == "send") {

                $name = $_POST ['name'];

                if (!$name || $name == '') {
                    $name_error = 'Please insert name';
                } else {
                    $name_error = '';

            }
            ?>

also this

<div title="Send" style="padding: 5px; text-align: left">
<form action="" method="post">
    <input type="hidden" name="action" value="send" />
    <table style="border: 0px;">
        <tr>
            <td style="color: white">Full name:<a class="notemptycolor">*</a></td>
            <td>
                <input type="text" value="<?= $name ?>" name="name"/>
                <?= !empty($name_error) ? '<div style="margin-top: 10px; margin-bottom: 10px; color: red;background-color: white" >' . $name_error . '</div>' : '' ?>
            </td>
        </tr>
    </table>
    <input type="image" name="submit" src="images/sendBtn.gif" style="float: right; margin-top:9px; margin-right:20px;">
</form>

Was it helpful?

Solution

Try:

          <?php
            $name = "";
            if (!empty($_POST['action']) && $_POST['action'] == "send") {

                $name = $_POST ['name'];

                if (!$name || $name == '') {
                    $name_error = 'Please insert name';
                } else {
                    $name_error = '';

            }
            ?>

OTHER TIPS

You're using $name in the form but it's not defined if the form isn't submit.

My suggestion would be:

<?php
$name = '';
$name_error = '';

if ( isset( $_POST['action'] ) && $_POST['action'] == "send" ) {

    $name = ( isset( $_POST['name'] ) ) ? $_POST ['name'] : '';

    if ( empty( $name ) ) 
        $name_error = 'Please insert name';

} ?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top