在php中使用bootstrap发生错误时如何显示错误

时间:2019-06-29 16:20:32

标签: php html css

我正在使用php和bootstrap建立联系表单,并且想在发生错误时显示bootstrap警报。所以我的问题是,我已经可以使用代码了,它可以检查错误,但是在错误发生之前会显示错误警报对话框

我尝试将错误对话框移到HTML下方,但仍然出现相同的错误

$email = $name = $subject = $message = '';

$errors = ['email' => '', 'name' => '', 'subject' => '', 'message' => ''];

if (isset($_POST['submit'])) {

    // check email
    if (empty($_POST['email'])) {
        $errors['email'] = "An email is required !";
    } else {
        $email = $_POST['email'];
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors['email'] = "Enter a validemail address !";
        }
    } 


<div class="form-group">

    <label for="email" class="bmd-label-floating">Email address</label>
    <input type="email" class="form-control" name="email" value="<?php htmlspecialchars($email)?>">
    <div class="mt-2 alert alert-warning alert-dismissible fade show" role="alert">
        <?php echo $errors['email'] ?>
    </div>
</div>

预期的行为应该是在发生错误时在错误对话框中显示错误,而不是在错误发生之前发生错误对话框

2 个答案:

答案 0 :(得分:0)

您想用if包装模式以检查是否确实存在错误。

<?php if($errors['email']): ?>
<div class="mt-2 alert alert-warning alert-dismissible fade show" role="alert">
    <?php echo $errors['email'] ?>
</div>
<?php endif; ?>

答案 1 :(得分:0)

在显示错误之前添加检查。像下面

<?php
if(isset($errors['email']) && $errors['email']!=''){ 
?>
<div class="mt-2 alert alert-warning alert-dismissible fade show" role="alert">
        <?php echo $errors['email']; ?>
</div>
<?php } ?>