【问题标题】:How to enter form data into a database using Ajax and PHP如何使用 Ajax 和 PHP 将表单数据输入数据库
【发布时间】:2017-11-10 07:53:27
【问题描述】:

我想使用 ajax 获取表单数据,然后将其提交到我的 php 页面,然后将其插入到我的数据库中。成功插入时,我想显示“您已成功注册”,失败时显示“注册失败”,如果您已经是会员,我会显示“已经是会员,请登录”。

由于某种原因,我的 ajax 代码无法按预期工作。它跳到最后一部分(else 语句甚至不关心 if 语句)。我的php代码是正确的。因为我已经单独测试过它并且工作正常。

有人可以为我建议一个解决方案或其他方法来完成此操作记住我不想转到另一个页面。

这是我的 JavaScript/jQuery 代码:

$(document).ready(function){
    //Signup Js
    $("#Register").click(function(){ //#Register is my submit button id
        var action = $("#sp-form").attr('action'); //#sp-form is the register form id.
        var spform_data = {
            myusername: $("#myusername").val(),
            myemail: $("#myemail").val(),
            mypassword: $("#mypassword").val() //Getting data from the input forms using their respective id's
        }

        $.ajax({
            type: "POST",
            url: action,
            data: spform_data,
            success: function(outcome)
            {
                if(outcome == "success"){
                    $("#sp-form").slideUp('slow', function(){
                        $("#message_sp").html('<p class="success">You have been registered successfully!</p><p style="color:#1c1c1c;">Redirecting....</p>');
                    });
                }
                else if(outcome == "alreadymember") {
                    $("#modal_signup").css("height","380");
                    $("#message_sp").html('<p class="error">ERROR: Email match found,Just Sign in.</p>');
                }
                else if(outcome == "failed"){
                    $("#modal_signup").css("height","380");
                    $("#message_sp").html('<p class="error">ERROR:  Failed to Register</p>');
                }
                else{
                    $("#modal_signup").css("height","380");
                    $("#message_sp").html('<p class="error">ERROR:  Unknown   ERROR</p>');
                }                
            }            
        });
        return false;
    });
});

这是我的 PHP/MySQLi 代码

<?php
if ($_POST)
{
    $host = "localhost";
    $user= "root";
    $password = " ";

    try {
        $conn = mysqli_connect($host , $user , $password) or die("unable to connect to Local Host"); //Establishing connection with the server
        $sql = mysqli_select_db($conn,'audacity') or die("unable to connect to database"); //selecting a database from the server #after connecting
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    $name = mysqli_real_escape_string($conn,$_POST['myusername']);
    $mail = mysqli_real_escape_string($conn,$_POST['myemail']);
    $pass = mysqli_real_escape_string($conn,$_POST['mypassword']);

    // Query of SQL
    $Query =mysqli_query($conn,"INSERT INTO  registration (Username,Email,Password) VALUES ('$name', '$mail' , '$pass')")) //if successful outcome is true
    if($Query ==true){
        echo "success";
    }
    elseif ($Query==false) {  #if failed
        $sqlbd = "SELECT Email FROM registration WHERE Email='$mail' ";
        $result = mysqli_query($conn,$sqlbd);

        if(mysqli_num_rows($result)==1){  //possible rsn for failure
            echo "alreadymember";             
        }
        else{
            echo "failed";  //unknown reason.
        }
    }
    mysqli_close($conn);
?>

问题出在哪里???

【问题讨论】:

  • 在成功函数的第一行插入console.log(outcome),看看你的控制台浏览器发生了什么。
  • 您的数据库有什么变化吗?
  • No.. 我的数据库没有变化
  • 你的问题可能出在你的 php 文件中。页面是否返回任何错误标头的错误消息?
  • 问题是你必须使用firebug工具来调试你的php代码。

标签: php jquery ajax mysqli


【解决方案1】:

我认为您必须在 ifs 语句的开头检查 num_rows 是否 ==1...您的 php 只需输入电子邮件然后检查 num 行作为 else 语句...您首先检查 num 行然后设置 if 语句或者您已经为您的电子邮件栏设置了唯一性?

【讨论】:

  • 是的,主键是电子邮件
【解决方案2】:

我可以确认您的代码有很多错误。 我附上了代码的更正版本;但是,我会假设(从 php 代码)目标是防止多次注册;如果是这种情况,则应检查您的逻辑。您在检查之前插入,因此检查代码永远不会运行。因此,在尝试插入之前进行检查。整体代码似乎不太好。 我只修复了错误,你应该处理逻辑。

JQuery $(document).ready(function () {

            $("#sp-form").submit(function (e) {
                return false;
            });
            $("#Register").click(function () {
                var action = $("#sp-form").attr('action'); //#sp-form 
is the register form id.

                var spform_data = {
                    myusername: $("#myusername").val(),
                    myemail: $("#myemail").val(),
                    mypassword: $("#mypassword").val()         
//Getting data from the input forms using their respective id's
                }


                $.ajax({
                    type: "POST",
                    url: action,
                    data: spform_data,
                    success: function (outcome)
                    {
                        if (outcome.indexOf("success")>=0) {
                            $("#sp-form").slideUp('slow', function () {
                                $("#message_sp").html('<p 
class="success">You have been registered successfully!</p><p 
style="color:#1c1c1c;">Redirecting....</p>');
                            });
                        }
                        else if (outcome.indexOf("alreadymember")>=0) {


                            $("#modal_signup").css("height", "380");
                            $("#message_sp").html('<p 
class="error">ERROR: Email match found,Just Sign in.</p>');


                        }

                        else if (outcome.indexOf("failed")>=0) {


                            $("#modal_signup").css("height", "380");
                            $("#message_sp").html('<p 
class="error">ERROR:  Failed to Register</p>');


                        }
                        else {


                            $("#modal_signup").css("height", "380");
                            $("#message_sp").html('<p 
class="error">Unknown Error</p>');
                        }

                    }

                });
                return false;


            });
        });

// Php
 $host = "localhost";
        $user = "root";
        $password = "";
        $conn = "";
        try {
            $conn = mysqli_connect($host, $user, $password) or 
die("unable to connect to Local Host"); //Establishing connection with 
the server

            $sql = mysqli_select_db($conn, 'audacity') or die("unable 
to connect to database"); //selecting a database from the server #after 
connecting
        } catch (Exception $e) {
            echo $e->getMessage();
        }


        $name = mysqli_real_escape_string($conn, $_POST['myusername']);
        $mail = mysqli_real_escape_string($conn, $_POST['myemail']);
        $pass = mysqli_real_escape_string($conn, $_POST['mypassword']);

        // Query of SQL


        $Query = mysqli_query($conn, "INSERT INTO  registration 
(Username,Email,Password) VALUES ('$name', '$mail' , '$pass')"); //if 
successful outcome is true
        if ($Query == true) {

            echo "success";
        } elseif ($Query == false) {  #if failed
            $sqlbd = "SELECT Email FROM registration WHERE 
Email='$mail' ";
            $result = mysqli_query($conn, $sqlbd);

            if (mysqli_num_rows($result) == 1) {  //possible rsn for 
failure
                echo "alreadymember";
            } else {

                echo "failed";  //unknown reason.
            }
        }

        mysqli_close($conn);
    }

【讨论】:

  • Yah Oluasa 我在检查之前插入了,因为我意识到如果您插入并且在数据库中找到匹配项。由于电子邮件是主键,因此不会插入您的数据
  • 但是非常感谢,我会比较你的逻辑和我的逻辑,并在必要时进行调整......谢谢兄弟不要删除你的评论
  • 好的,我明白了。无论如何,您应该在插入之前放置检查,所以如果没有找到记录,那么您可以插入。它更清洁。
  • 好的,我会放在前面
猜你喜欢
  • 2011-06-16
  • 2013-12-07
  • 2015-09-28
  • 1970-01-01
  • 1970-01-01
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多