在使用 onsubmit 插入数据库之前如何验证表单的输入

How can I verify the input of a form before insert in a database with onsubmit

我有一个注册表单,我想在将数据输入数据库之前验证它。 验证phone号码是否全是数字,然后比对数据库中的用户名,看是否已经存在,如果都好,就去数据库注册。

起初,我用的是这个:

<?php 

session_start();
include("connection.php");
include("fonctions.php");

    if($_SERVER['REQUEST_METHOD'] == "POST")
    {
        //Récupérer les data de la variable post
        $prenom = $_POST['txtPrenom'];
        mysqli_real_escape_string($con,$prenom);
        $nom = $_POST['txtNom'];
        mysqli_real_escape_string($con,$nom);
        $adresseMail = $_POST['txtAdresseMail'];
        mysqli_real_escape_string($con,$adresseMail);
        $numeroGSM = $_POST['txtGSM'];
        mysqli_real_escape_string($con,$numeroGSM);
        $identifiant = $_POST['txtIdentifiant'];
        mysqli_real_escape_string($con,$identifiant);
        $motDePasse = $_POST['txtMotDePasse'];
        mysqli_real_escape_string($con,$motDePasse);
        $refClient = random_num(20);
        mysqli_real_escape_string($con,$refClient);
        $invite = 0;
        mysqli_real_escape_string($con,$invite);


        if (!empty($prenom) && !empty($nom) && !empty($adresseMail) && !empty($numeroGSM) && !empty($identifiant) && !empty($motDePasse))
        {
            if (!is_numeric($numeroGSM))
            {

                //alert("Numéro de GSM invalide");

            }
            else 
            {
                $identifiantPresent = "SELECT identifiant FROM tblclient where identifiant = '".$identifiant."' ";
                $result = mysqli_query($con, $identifiantPresent);

                if (mysqli_num_rows($result) > 0)
                {
                    alert("Identifiant existe déjà");

                }
                else
                {
                    //Enregistrement dans la base de données
                    $query = "insert into tblclient(refClient,prenom,nom,adresseMail,numeroGSM,identifiant,motDePasse,invite) values ('$refClient','$prenom','$nom','$adresseMail','$numeroGSM','$identifiant','$motDePasse','$invite')";
                    mysqli_query($con, $query);
                    alertHeader("Compte crée avec succès","../index.php");
                }
            }
        }
        else
        {
            alert("Veuillez remplir tout les champs");
        }
    }
?>

<!DOCTYPE html>

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>La Cour des Dames</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <link href="/CSS/StyleAccueil.css" rel="stylesheet" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    </head>
    <body>
            <div id="Contenaire">
                <header id="FondBanniere">
                    <img src="../Images/Logo.jpeg" id="Banniere">
                </header>

        <link href="../CSS/StyleAccueil.css" rel="stylesheet" />

    <div class="persoNav">
        <ul class="nav justify-content-center">
          <li class="nav-item">
            <button id="btnAccueil" class="nav-link">Accueil</button>
          </li>
        </ul>
    </div>
<form method="post">
    <table class="tableauInscription">
        <tr>
            <td colspan="2"><h3 style="text-align:center;">Formulaire d'inscription</h3></td>
        </tr>

        <tr>
            <td class="coteGauche">Prenom :</td>
            <td><input type="TextBox" name="txtPrenom" id="txtPrenom" CssClass="form-control" placeholder="Prenom"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Nom :</td>
            <td><input type="TextBox" name="txtNom" id="txtNom" CssClass="form-control" placeholder="Nom"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Adresse email :</td>
            <td><input type="email" name="txtAdresseMail" id="txtAdresseMail" CssClass="form-control" placeholder="Adresse email"></td>
        </tr>
        
        <tr>
            <td  class="coteGauche">GSM min 7 :</td>
            <td><input type="TextBox" name="txtGSM" id="txtGSM" CssClass="form-control" placeholder="GSM" minlength="7"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Identifiant :</td>
            <td><input type="TextBox" name="txtIdentifiant" id="txtIdentifiant" CssClass="form-control" placeholder="Identifiant"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Mot de passe : </td>
            <td><input type="Password" name="txtMotDePasse" id="txtMotDePasse" CssClass="form-control" placeholder="Mot de passe"></td>
        </tr>

        <tr>
            <td  class="coteGauche"></td>
            <td style="padding-left:33px; padding-top:10px; padding-bottom:10px;">
                <button type="submit" id="btnCreerCompte" class="btn btn-dark">Créer le compte</button></td>
        </tr>
    </table>
</form>
    </body>

    <!-- PARTIE SCRIPT -->

    <script type="text/javascript">
    document.getElementById("btnAccueil").onclick = function () {
        location.href = "../index.php";
    };
    </script>

</html>

但问题是显示警报后页面正在刷新,所以我搜索它并找到了“onsubmit”,但现在的问题是我需要在我的函数中完成所有这些:

<?php 

session_start();
include("connection.php");
include("fonctions.php");

?>

<!DOCTYPE html>

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title>La Cour des Dames</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <link href="/CSS/StyleAccueil.css" rel="stylesheet" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

  <script type="text/javascript">
    function valide_GSM() {
        var prenom = document.getElementById("txtPrenom").value;
        var nom = document.getElementById("txtNom").value;
        var mail = document.getElementById("txtAdresseMail").value;
        var numGSM = document.getElementById("txtGSM").value;
        var identifiant = document.getElementById("txtIdentifiant").value;
        var motDePasse = document.getElementById("txtMotDePasse").value;


        if (!empty(prenom) && !empty(nom) && !empty(adresseMail) && !empty(numeroGSM) && !empty(identifiant) && !empty(motDePasse))
        {
            if (isNaN(numGSM))
            {
                alert("Numéro de gsm non valide");
                //Phone number invalid
                document.getElementById("txtGSM").focus();
                return false;
            }
            else 
            {
                identifiantPresent = "SELECT identifiant FROM tblclient where identifiant = '".identifiant."' ";
                result = mysqli_query(con, identifiantPresent);

                if (mysqli_num_rows(result) > 0)
                {
                    alert("Identifiant existe déjà");
                    //Username already existing

                }
                else
                {
                    //Enregistrement dans la base de données
                    //Registration in the database
                    query = "insert into tblclient(refClient,prenom,nom,adresseMail,numeroGSM,identifiant,motDePasse,invite) values ('refClient','prenom','nom','adresseMail','numeroGSM','identifiant','motDePasse','invite')";
                    mysqli_query(con, query);
                    alertHeader("Compte crée avec succès","../index.php");
                    //Account created successfully
                }
            }
        }
        else
        {
            alert("Veuillez remplir tout les champs");
            //Please fill all input box
        }
        return true;
    }
  </script>

    </head>
    <body>
            <div id="Contenaire">
                <header id="FondBanniere">
                    <img src="../Images/Logo.jpeg" id="Banniere">
                </header>

        <link href="../CSS/StyleAccueil.css" rel="stylesheet" />

    <div class="persoNav">
        <ul class="nav justify-content-center">
          <li class="nav-item">
            <button id="btnAccueil" class="nav-link">Accueil</button>
          </li>
        </ul>
    </div>
<form method="post" onsubmit="return valide_GSM();">
    <table class="tableauInscription">
        <tr>
            <td colspan="2"><h3 style="text-align:center;">Formulaire d'inscription</h3></td>
        </tr>

        <tr>
            <td class="coteGauche">Prenom :</td>
            <td><input type="TextBox" name="txtPrenom" id="txtPrenom" CssClass="form-control" placeholder="Prenom"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Nom :</td>
            <td><input type="TextBox" name="txtNom" id="txtNom" CssClass="form-control" placeholder="Nom"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Adresse email :</td>
            <td><input type="email" name="txtAdresseMail" id="txtAdresseMail" CssClass="form-control" placeholder="Adresse email"></td>
        </tr>
        
        <tr>
            <td  class="coteGauche">GSM min 7 :</td>
            <td><input type="TextBox" name="txtGSM" id="txtGSM" CssClass="form-control" placeholder="GSM" minlength="7"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Identifiant :</td>
            <td><input type="TextBox" name="txtIdentifiant" id="txtIdentifiant" CssClass="form-control" placeholder="Identifiant"></td>
        </tr>

        <tr>
            <td  class="coteGauche">Mot de passe : </td>
            <td><input type="Password" name="txtMotDePasse" id="txtMotDePasse" CssClass="form-control" placeholder="Mot de passe"></td>
        </tr>

        <tr>
            <td  class="coteGauche"></td>
            <td style="padding-left:33px; padding-top:10px; padding-bottom:10px;">
                <button type="submit" id="btnCreerCompte" class="btn btn-dark">Créer le compte</button></td>
        </tr>
    </table>
</form>
    </body>

    <!-- PARTIE SCRIPT -->

    <script type="text/javascript">
    document.getElementById("btnAccueil").onclick = function () {
        location.href = "../index.php";
    };
    </script>

</html>

显然这行不通,但我有点卡住了,我不知道如何适应或在哪里寻找我的研究。谢谢大家的关注。

我想你用错了变量名。例如,在你的 JS(IF 语句)中,变量是 mail 而不是 adresseMail。更正这些变量,然后再试一次。

此外,在您的函数中,每当您显示无效字段或任何字段的警报时,只需添加 return false。这将确保在出现错误时处理停止并且函数默认情况下不会 return true

更改如下:

var mail = document.getElementById("txtAdresseMail").value; // rename to adresseMail
var numGSM = document.getElementById("txtGSM").value; // rename to numeroGSM
...
...
else
    {
        alert("Veuillez remplir tout les champs");
        //Please fill all input box
        return false; // ADD THIS
    }

将您的 JavaScript 与 PHP 代码分开,以使其更具可读性。

这是一个示例 Ajax 代码。您将需要另一个 php check-user.php 来检查用户是否存在。

注:

  1. 尝试使用Ajax,从简单开始。它可以改善整体用户体验。 AJAX 允许您在不刷新页面的情况下与服务器进行检查。试试这个简单的 example。但请注意,用户可以禁用 javascript,因此在客户端和服务器端验证表单始终是一个好主意,只需保持您的 php 验证即可。
  2. 请注意,您的代码对 SQL Injections. You should use parameterized prepared statements instead. Check this 开放。

表单验证,其中 JQueryAjax mainForm.php

$('#btnCreerCompte').on('click',function(e){
   //prevent submitting form
   e.preventDefault();
  
   //Get Input Values
   var prenom = document.getElementById("txtPrenom").value;
   var nom = document.getElementById("txtNom").value;
   var mail = document.getElementById("txtAdresseMail").value;
   var numGSM = document.getElementById("txtGSM").value;
   var identifiant = document.getElementById("txtIdentifiant").value;
   var motDePasse = document.getElementById("txtMotDePasse").value;
   
   //Form Validation
   if (prenom && nom && mail && numGSM && identifiant && motDePasse){
       if (isNaN(numGSM)){
           alert("Numéro de gsm non valide");
           //Phone number invalid
           document.getElementById("txtGSM").focus();
           return false;
       }
       else{
           //Call Ajax to check if user existed
           $.ajax({ 
             type    : "POST",
             url     : "check-user.php",
             dataType: "json",
             data: {
              //data you need for php query, to check if user existed
              //Use $_POST['identifiant'] in check-user.php
              identifiant: identifiant
             },           
             success:function(result) {
               // alert(result.msg);
               if (result.msg == "Success"){
                 e.preventDefault();
                 //Submit form if user not existed
                 $('form').submit(); 
               }
               else if (result.msg == "Failed"){
                 e.preventDefault();
                 alert("User Existed!");
               }
             }
           });
       }
   }
   else{
      alert("Veuillez remplir tout les champs");
      return false;
   }
   
});

PHP: 检查-user.php

<?php
   //DB Connection
   $con = ..;  

   $identifiant = $_POST['identifiant'];

   $identifiantPresent = "SELECT identifiant FROM tblclient where identifiant = '".$identifiant."' ";
   $result = mysqli_query($con, $identifiantPresent);

   if (mysqli_num_rows($result) > 0){
      $arr = array('msg' => "Failed");
   }
   else{
      $arr = array('msg' => "Success");
   }

   echo json_encode($arr);
?>