数据没有输入数据库..?

时间:2015-12-02 05:23:15

标签: php jquery html json

我正在尝试使用php,json和jquery请求为我的用户创建一个注册表单我认为php代码很好但我认为问题是jquery函数..我是新来的这一切都可以帮助我了...请原谅我,如果我错了,请随时提出建议。

    **php code goes here:**

            <!--register.php-->
       <?php



require_once 'DB_Functions.php';
   $db = new DB_Functions();

    // json response array
    $response = array("error" => FALSE);
    if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['mobile'])) {
        var_dump('here');
        // receiving the post params
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $mobile = $_POST['mobile'];

        // check if user is already existed with the same email
        if ($db->isUserExisted($email)) {
            // user already existed
            $response["error"] = TRUE;
            $response["error_msg"] = "User already existed with " . $email;
            echo json_encode($response);
        } else {
            // create a new user
            $user = $db->storeUser($fname, $lname, $email, $password, $mobile);
            if ($user) {
                // user stored successfully
                $response["error"] = FALSE;
                $response["uid"] = $user["id"];
                $response["user"]["fname"] = $user["fname"];
                $response["user"]["lname"] = $user["lname"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = TRUE;
                $response["error_msg"] = "Unknown error occurred in registration!";
                echo json_encode($response);
            }
        }
    } else {
        $response["error"] = TRUE;
        $response["error_msg"] = "Required parameters (fname, lname, email, password or mobile) is missing!";
        echo json_encode($response);
    }
    ?>

听到了DB_Functions.php代码......!

        <?php

class DB_Functions {

    private $conn;

    // constructor
    function __construct() {
        require_once 'DB_Connect.php';
        // connecting to database
        $db = new Db_Connect();
        $this->conn = $db->connect();
    }

    // destructor
    function __destruct() {

    }

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($fname, $lname, $email, $password, $mobile) {
        $uuid = uniqid('', true);
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
         $stmt = $this->conn->prepare("INSERT INTO users(fname, lname, email, password, mobile) 
          VALUES('".$fname."', '".$lname."', '".$email."', '".$password."', '".$mobile."')";
        $result = $stmt->execute();
        $stmt->close();

    // check for successful store
       if ($result) {
            $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = '$email'");
            $stmt->execute();
            $user = $stmt->get_result()->fetch_assoc();
            $stmt->close();

            return $user;
        } else {
            return false;
        }
    }
  }

数据插入前端部分

           <html>
        <head>
           <title>jQuery Test</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
         <script type="text/javascript">
         $(document).ready(function() {

                $("#submit").click(function(){

                $.ajax({
                url: "localhost/web_login_api/register.php",
                type: "POST",
                data: {
                    fname: $("#fname").val(),
                    lname: $("#lname").val(),
                    email: $("#email").val(),
                    password: $("#password").val(),
                    mobile: $("#mobile").val()
                },
                dataType: "JSON",
                success: function (jsonStr) {
                    $("#result").text(JSON.stringify(jsonStr));
                }
            });

        }); 

        });
         </script>
     </head>

     <body>
        <div id = "result"></div>
        <!--html body-->
        <form name = "register" action = "#" id = "register" method = "POST">
            <label>First name:</label>
            <input type = text name = "fname" id = "fname">
            <label>Last name:</label>
            <input type = "text" name = "lname" id = "lname">
            <label>E-mail:</label>
            <input type = "email" name = "email" id = "email">
            <label>Password</label>
            <input type = "password" name = "password" id = "password">
            <label>Mobile no:</label>
            <input type = "text" name = "mobile" id = "mobile">
             <input type="button" value="Insert" name="submit" id="submit" href = "#">
            </form>
     </body>
     </html>

3 个答案:

答案 0 :(得分:0)

您从HTML代码传递的值中没有密码字段,在您的php中,您正在尝试读取密码值。从您的php中删除密码字段或在HTML中添加密码字段以获得所需的输出。

-Thanks

答案 1 :(得分:0)

我认为你的jQuery没有任何问题,

调试ajax时的一些有用提示是使用firebug或chromes网络窗格来确保正在发送正确的帖子变量,并确保服务器端脚本中没有返回错误。

潜在问题

我确实看到了您的退货类型的问题。如果你从你的返回JSON  “register.php”

这可能会产生问题。 简单的解决方案,将您的内容类型标题设置为JSON:

header('Content-Type: application/json');
echo json_encode($response);

*请注意,必须在回显或打印任何内容之前完成。

文档:http://php.net/manual/en/function.header.php

<强>建议

  • 将事件绑定到提交处理程序
  • 在ajax方法之外构造对象
  • 运行前端验证
  • 使用$ .post包装器
<form id="register" method="post" action="#">
    <input id="name" type="text" name="name" placeholder="Enter Name" />
    <input id="password" type="password" name="password" />
    <input type="submit" name="submit" value="Sign Up" />
</form>
<script>
    $(function(){
        //ajax on form submit
        $("#register").submit(function (event) {
            //prevent default page reload
            event.preventDefault();
            //create post object
            var postUserRegistrationData = {
                name: $("#name").val(),
                password: $("#password").val()
            };

            //for debugging dump it before sending
            console.log(postUserRegistrationData);

            //validate it (should be abstracted)
            if(!!postUserRegistrationData.name && !!postUserRegistrationData.password) {
                //post to the server
                $.post( "backend.php", postUserRegistrationData, function(data){
                    console.log("The reply:"+data);
                });
            } else {
                //throw if not valid
                alert("Validation Trigger");
            }
        });
    });
</script>

答案 2 :(得分:0)

好的,现在试试..编辑..

DB_Functions.php 文件

<?php

 class DB_Functions {
    private $db;

    // constructor
    function __construct() {
     require_once 'config.php';
     try {
        $hostname = DB_HOST ;
        $dbname   = DB_DATABASE;
        $this->db = new PDO("mysql:host=$hostname;dbname=$dbname", DB_USER, DB_PASSWORD);
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }
}

    /**
     * Storing new user
     * returns user details
     */
    public function storeUser($fname, $lname, $email, $password, $mobile) {  
        try {
            $hash = md5($password);
            $sql = "INSERT INTO db_name(fname, lname, email, password, mobile) VALUES ('$fname', '$lname', '$email', '$hash', $mobile)";
            $result = $this->db->query($sql);

            if ($result) {
                // get user details
                $id = $this->db->lastInsertId(); //last inserted id
                $sql = "SELECT * FROM db_name WHERE email = $email";
                $result = $this->db->query($sql);
                $no_of_rows = $result->fetchColumn();
                // returns confirmation message if completed
                if ($no_of_rows > 0) {
                    return "existsandcompleted";
                }
            }

        }
        catch (Exception $e) {
            $error = 'Error accessing database: ' . $e->getMessage();

        }

    }
}

?>

在主档

<?php
   require_once 'DB_Functions.php';
   $db = new DB_Functions();

    // json response array
    $response = array("error" => FALSE);
    if (isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['mobile'])) {

        // receiving the post params
        $fname = $_POST['fname'];
        $lname = $_POST['lname'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $mobile = $_POST['mobile'];

         // create a new user
        $user = $db->storeUser($fname, $lname, $email, $password, $mobile);

        if ($user) {
            // user stored successfully
            $response["error"] = FALSE;
            $response["uid"] = $user["id"];
            $response["user"]["fname"] = $user["fname"];
            $response["user"]["lname"] = $user["lname"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = TRUE;
            $response["error_msg"] = "Unknown error occurred in registration!";
            echo json_encode($response);
        }

    } else {
        $response["error"] = TRUE;
        $response["error_msg"] = "Required parameters (fname, lname, email, password or mobile) is missing!";
        echo json_encode($response);
    }
?>

这完全有用..如果这不起作用那么你在某处有语法错误...另外,如果你有int数据类型到数字字段然后不要生成字符串..希望这工作。 !干杯!