无法在数据库中存储数据

时间:2018-06-07 09:19:22

标签: php html ajax mysqli

我正在使用AJAX创建一个PHP注册表单,我粘贴的以下代码无法正常工作。我对这个AJAX概念完全不熟悉            当我单击注册按钮时,它将不响应并执行任何操作,甚至在数据库中也不会存储值。我已经搜索了很多这个AJAX概念。            但我似乎没有得到我想要的结果。拜托,任何人都可以帮助我。我在哪里做错了什么?提前谢谢!

的index.php

                    <!DOCTYPE HTML>  
                    <html>
                    <head>
                        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
                        <script src="script.js"></script>
                    <style>
                    .error {
                        color:red;
                    }

                    .button {
                        background-color: #4CAF50;
                        border: none;
                        color: white;
                        padding: 10px 25px;
                        text-align: center;
                        text-decoration: none;
                        display: inline-block;
                        font-size: 16px;
                        margin: 4px 2px;
                        cursor: pointer;
                    }
                    .div1 {

                        margin-top: -19px;
                        margin-bottom: -25px;
                        margin-left: -19px; 
                    }

                    .copy {
                        border-radius: 4px;
                        padding: 6px 20px;
                       border-style: ridge;
                    }

                    .copy1{
                         border-radius: 4px;
                         padding: 6px 28px;
                         border-style: ridge;
                    }

                    .copy2{
                         border-radius: 4px;
                         padding: 4px 2px;

                    }
                    </style>
                    </head>
                    <body style="background-color: #f2f2f2;">  





                <?php
                // define variables and set to empty values
                include_once 'connect.php';

                $nameErr = $emailErr = $usernameErr = $passwordErr = $ageErr = "" ;
                $name = $email = $username = $password =  $age =  "";

                 if (isset($_POST['submit'])) {
                  if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
                  } else {
                    $name = test_input($_POST["name"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                      $nameErr = "Only letters"; 
                    }
                  }

                   if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
                  } else {
                    $email = test_input($_POST["email"]);
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                      $emailErr = "Invalid email format"; 
                    }
                  }

                  if (empty($_POST["username"])) {
                    $usernameErr = "Username is required";
                  } else {
                    $username = test_input($_POST["username"]);
                     // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
                      $usernameErr = "Only letters"; 
                    }
                  }

                  if (empty($_POST["password"])) {
                    $passwordErr = "Password is required";
                  } else {
                    $password = test_input($_POST["password"]);
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    // check weather password is alphanumeric
                  if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{6,}$/', $password))
                  {
                    $passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
                  }
                  }



                    if (empty($_POST["age"])) {
                        $ageErr = "Age is required";
                    } 
                    elseif($_POST["age"]< 17 ) {
                        $ageErr = "Age should be above 18 years";
                    }
                    else {
                            $age = $_POST["age"];
                            }





                if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" &&  $ageErr == "")
                  { 
                $check="SELECT * FROM users WHERE username = '$_POST[username]'";
                $rs = mysqli_query($mysqli,$check);
                $da = mysqli_fetch_array($rs, MYSQLI_NUM);
                if($da[0] > 0) {
                    echo "Username Already in Exists<br/>";
                }

                else
                {
                    $sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
                             VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";

                        if (mysqli_query($mysqli, $sql)) {
                        echo "Registered successfully";
                        } else {
                        echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
                        } 
                        mysqli_close($mysqli);
                }
                  }
                }

                function test_input($data) {
                  $data = trim($data);
                  $data = stripslashes($data);
                  $data = htmlspecialchars($data);
                  return $data;
                }
                ?>

                <div style="padding-left: 250px" class="div1">

                    <h2 style="color:#009999">Registration Form :</h2>
                    <p><span class="error">All fields are required </span></p>
                    <form action="" method="post" enctype="multipart/form-data">

                            <span style="color:#0099ff">Name: </span>
                            <input type="text" name="name" class= "copy" style="margin-left: 52px"  value ="<?php 
                                     if (isset($name)) 
                                      echo $name; 
                                 ?>">
                            <span class="error"> <?php echo $nameErr;?></span>
                            <br><br>

                            <span style="color:#0099ff"> E-mail: </span>
                            <input type="text" name="email" class= "copy" style="margin-left: 48px"  value ="<?php 
                                     if (isset($email)) 
                                      echo $email; 
                                 ?>">
                            <span class="error"><?php echo $emailErr;?></span>
                            <br><br>

                            <span style="color:#0099ff"> Username: </span>
                            <input type="text" name="username"  class= "copy" style="margin-left:26px"  value ="<?php 
                                     if (isset($username)) 
                                      echo $username; 
                                 ?>">
                            <span class="error"> <?php echo $usernameErr;?></span>
                            <br><br>

                            <span style="color:#0099ff"> Password: </span>
                            <input type="password" name="password"  class= "copy" style="margin-left:30px">
                            <span class="error"> <?php echo $passwordErr;?></span>
                            <br><br>



                            <span style="color:#0099ff">  Age : </span>
                            <input type="number" name="age"  class= "copy" style="margin-left:62px"  value ="<?php 
                                     if (isset($age)) 
                                      echo $age; 
                                 ?>">
                            <span class="error"> <?php echo $ageErr;?></span>
                            <br><br>



                            <input type="button" class="submit" name="submit" value="submit">   


                        </form>
                </div>
                </body>


                </html> 

的script.js

        $(document).ready(function(){
        $(".submit").click(function(){
        var name = $("name").val();
        var email = $("email").val();
        var username = $("username").val();
        var password = $("password").val();
        var age = $("age").val();
        // Returns successful data submission message when the entered information is stored in database.
        var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
        var dataString = $("form").serialize();
        if(name==''|| email==''|| username==''|| password==''|| age=='')
        {

        // AJAX Code To Submit Form.
        $.ajax({
        type: "POST",
        url: "index.php",
        data: dataString,
        cache: false,
        success: function(result){
        alert(result);
        }
        });
        }
        return false;
        });
        });

connect.php

        <?php


       $databaseHost = 'localhost';
       $databaseName = 'ajax1';
       $databaseUsername = 'root';
       $databasePassword = '';

       $mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);

       ?>

2 个答案:

答案 0 :(得分:0)

试试这个...我希望它能帮到你..

<强>的index.php

 <!DOCTYPE HTML>  
                    <html>
                    <head>
                        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
                        <script src="script.js"></script>
                    <style>
                    .error {
                        color:red;
                    }

                    .button {
                        background-color: #4CAF50;
                        border: none;
                        color: white;
                        padding: 10px 25px;
                        text-align: center;
                        text-decoration: none;
                        display: inline-block;
                        font-size: 16px;
                        margin: 4px 2px;
                        cursor: pointer;
                    }
                    .div1 {

                        margin-top: -19px;
                        margin-bottom: -25px;
                        margin-left: -19px; 
                    }

                    .copy {
                        border-radius: 4px;
                        padding: 6px 20px;
                       border-style: ridge;
                    }

                    .copy1{
                         border-radius: 4px;
                         padding: 6px 28px;
                         border-style: ridge;
                    }

                    .copy2{
                         border-radius: 4px;
                         padding: 4px 2px;

                    }
                    </style>
                    </head>
                    <body style="background-color: #f2f2f2;">  






                <div style="padding-left: 250px" class="div1">

                    <h2 style="color:#009999">Registration Form :</h2>
                    <p><span class="error">All fields are required </span></p>
                    <form action="" method="post" enctype="multipart/form-data">

                            <span style="color:#0099ff">Name: </span>
                            <input type="text" name="name" class= "name copy" style="margin-left: 52px"  value ="">
                            <span class="namee error"> </span>
                            <br><br>

                            <span style="color:#0099ff"> E-mail: </span>
                            <input type="text" name="email" class= "email copy" style="margin-left: 48px"  value ="">
                            <span class="emaile error"></span>
                            <br><br>

                            <span style="color:#0099ff"> Username: </span>
                            <input type="text" name="username"  class= "username copy" style="margin-left:26px"  value ="">
                            <span class="usernamee error"></span>
                            <br><br>

                            <span style="color:#0099ff"> Password: </span>
                            <input type="password" name="password"  class= "password copy" style="margin-left:30px">
                            <span class="passworde error"> </span>
                            <br><br>



                            <span style="color:#0099ff">  Age : </span>
                            <input type="number" name="age"  class= "age copy" style="margin-left:62px"  value ="">
                            <span class="agee error"> </span>
                            <br><br>



                            <input type="button" class="submit" name="submit" value="submit">   


                        </form>
                </div>
                </body>
<script>
    $(document).ready(function(){
        $(".submit").click(function(){

        var name = $(".name").val();
        var email = $(".email").val();
        var username = $(".username").val();
        var password = $(".password").val();
        var age = $(".age").val();

    if(name==''){$('.namee').text('fill value'); return  false} 
    if(email==''){$('.emaile').text('fill value'); return  false}   
    if(username==''){$('.usernamee').text('fill value'); return  false} 
    if(password==''){$('.passworde').text('fill value'); return  false} 
    if(age==''){$('.agee').text('fill value'); return  false}   



        // Returns successful data submission message when the entered information is stored in database.
        var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;


        // AJAX Code To Submit Form.
        $.ajax({
        type: "POST",
        url: "gethint.php",
        data: dataString,
        cache: false,
        success: function(result){
        alert(result);
        }
        });

        });
        });
</script>


                </html> 

<强> gethint.php

<?php



$mysqli  = mysqli_connect("localhost","root","","test");



$username =$_POST["username"];
$hashed_password=$_POST["password"];
$email=$_POST["email"];
$name=$_POST["name"];
$age=$_POST["age"];

                $check="SELECT * FROM users WHERE username = '$_POST[username]'";
                $rs = mysqli_query($mysqli,$check);
                $da = mysqli_fetch_array($rs, MYSQLI_NUM);
                if($da[0] > 0) {
                    echo "Username Already in Exists<br/>";
                }
                else
                {
                    $sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
                             VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";

                        if (mysqli_query($mysqli, $sql)) {
                        echo "Registered successfully";
                        } else {
                        echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
                        } 
                        mysqli_close($mysqli);
                }


?>

答案 1 :(得分:-1)

问题是当你第一次运行index.php文件时,php部分被执行。所以为php部分创建一个新文件。

从w3schools.com获取额外帮助

https://www.w3schools.com/php/php_ajax_php.asp