繁体   English   中英

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

[英]How to display php form validation errors beside the form?

我创建了一个注册表单,该表单可以通过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函数,而无需刷新页面。 读这个

如果您不想使用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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM