如何在表单旁边显示 php 表单验证错误

How to display php form validation errors beside the form?

本文关键字:表单 php 验证 错误 显示      更新时间:2023-09-26

我创建了一个由JavaScript和PHP验证的注册表单。每当发生任何javascript表单验证错误(例如用户名是必需的)时,它都会显示在表单旁边,但是当发生任何php验证错误(例如用户名已经存在)时,它会显示在另一个链接上。如何在表单旁边显示 php 验证错误?

<?php
 include('configdb.php');
 if(isset($_POST['submit']))
 {
 checks if the username is in use
if (!get_magic_quotes_gpc()) {
    $_POST['username'] = addslashes($_POST['username']);
}
 $usercheck = $_POST['username'];
 $sql1 = "SELECT username FROM users WHERE username = '$usercheck'"; 
 $result1 = mysqli_query($mysqli,$sql1) or die(mysqli_error());

//if the name exists it gives an error
if (mysqli_num_rows($result1) != 0) {
    die('Sorry, the username '.$_POST['username'].' is already in use.');
    }
     } 
如果你

不想使用ajax,这是另一种选择。它可以用php完成,但用户需要重新加载页面才能看到错误。

为此,html 表单代码和 php 验证代码必须放在同一个文件中。

<?php 
    $error = false;
    if(isset($_POST['submit'])){                
        // your validation
            // if something wrong
            $error = true;  
    }
?>
<form action="validation_checking.php" method="post">
    <?php
        if($error)
        { echo '<p style="color:red;">Sorry, the username '.$_POST['username'].' is already in use.</p>'; } 
    ?>
    <input type="text" name="username"> 
    <input type="submit" value="submit">
</form>

您必须使用 ajax 在不刷新页面的情况下执行 php 函数。阅读此内容