Pregunta

if(!empty($_POST))
{
if(empty($_POST['username'])) {die("Please enter a username.");}
....

Result is blank page - with the above alert.
I want to keep the form on the page. Something like:

if(empty($_POST['username']))?> <div id="info"><?php{echo "Please enter a username"};?></div> 

So, just write an info, and stop the code execution from this point.

¿Fue útil?

Solución 2

Rather than "stopping execution" on a single validation error, get all the errors and display them to the user:

<?php
if (!empty($_POST))
{
    // validate form
    $errors = array();

    if (empty($_POST['username']))
    {
        $errors['username'] = 'Please enter a username.';
    }

    if (empty($_POST['address']))
    {
        $errors['address'] = 'Please enter an address.';
    }

    if (empty($errors))
    {
        // save to database then redirect
    }
}

?>
<form>
    Username:<br />
    <input type="text" name="username" value="" /><br />
<?php if (!empty($errors['username'])): ?>
    <div class="error">
        <?php echo $errors['username'] ?>
    </div>
<?php endif ?>

    Address:<br />
    <input type="text" name="address" value="" /><br />
<?php if (!empty($errors['address'])): ?>
    <div class="error">
        <?php echo $errors['address'] ?>
    </div>
<?php endif ?>
</form>

Otros consejos

To Stop execution but you can use:

die( ' <div id="info">Please enter a username</div> ');

To allow the rest of the page to load you can use:

$errors = array();
if(empty($_POST['username'])) { 
    $errors[] = 'Please enter your username'; 
}

Then later in your html you can add

foreach($errors as $error){
    echo "<div class='error'>$error</div>;
}

Set some flag and returns/redirects to the same page. On the same page (script with form), check for the flag set and display the message.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top