插入查询在php中被触发两次

时间:2016-12-08 12:14:32

标签: php mysql

我正在尝试insert使用PHP将数据形成MySQL,但不知怎的insert查询被解雇两次。我已经在下面添加了我的代码...请帮助如果有人知道解决方案......

<?php
class Product{

// database connection and table name
private $conn;
private $table_name = "lspl_user_profile";

// object properties
public $id;
public $fname;
public $lname;
public $job;
public $dept;
public $email;
public $password;

public function __construct($db){
    $this->conn = $db;
}

public function create(){
    try{

        // insert query
        $query = "INSERT INTO lspl_user_profile
            SET fname=:fname, lname=:lname, job=:job, dept=:dept, email=:email, password=:password";

        // prepare query for execution
        $stmt = $this->conn->prepare($query);

        // sanitize
        $fname=htmlspecialchars(strip_tags($this->fname));
        $lname=htmlspecialchars(strip_tags($this->lname));
        $job=htmlspecialchars(strip_tags($this->job));
        $dept=htmlspecialchars(strip_tags($this->dept));
        $email=htmlspecialchars(strip_tags($this->email));
        $password=htmlspecialchars(strip_tags($this->password));



        // bind the parameters
        $stmt->bindParam(':fname', $fname);
        $stmt->bindParam(':lname', $lname);
        $stmt->bindParam(':job', $job);
        $stmt->bindParam(':dept', $dept);
        $stmt->bindParam(':email', $email);
        $stmt->bindParam(':password', $password); 


        // Execute the query

       if(empty($fname) ||empty($lname) || empty($job) ||empty($dept) ||empty($email) || empty($password) )
       {
           return false;
       }
       else
       {
           $stmt->execute();
           mysqli_close($conn);
            return true;
       }
    }
    // show error if any
    catch(PDOException $exception){
        die('ERROR: ' . $exception->getMessage());
    }
}
}

?>

这是create_product.php文件......

 <?php  
  if($_POST){

// include core configuration
include_once '../config/core.php';

// include database connection
include_once '../config/database.php';

// product object
include_once '../objects/product.php';

// class instance
$database = new Database();
$db = $database->getConnection();
$product = new Product($db);

// set product property values
$product->fname = $_POST['fname'];
$product->lname = $_POST['lname'];
$product->job = $_POST['job'];
$product->dept = $_POST['dept'];
$product->email = $_POST['email'];
$product->password = $_POST['password'];

// create the product
echo $product->create() ? "true" : "false";
}   
?>

此方法将参数发送到create_product.php

 $.post("api/create_product.php", {
        fname: this.state.fname,
        lname: this.state.lname,
        job: this.state.job,
        dept: this.state.dept,
        email: this.state.email,
        password: this.state.password
        }
);

1 个答案:

答案 0 :(得分:0)

谢谢,人们......问题得到了解决。实际上,我在HTML中犯了一个愚蠢的错误,导致post方法调用两次。

特别感谢ADyson ..