来自表单提交的数据无法插入数据库行

时间:2019-02-16 17:14:56

标签: javascript php ajax

我正在尝试使用ajax php和mysql,pdo在我的产品数据库中插入新产品。表单位于另一个html文件中,并在按下添加产品按钮后立即以引导程序模式加载。

下面是表格

    const PostSchema = new Schema({
      user: {
        type: Schema.Types.ObjectId,
        ref: "users"
      },
      text: {
        type: String,
        required: true
      },
      likes: [
        {
          user: {
            type: Schema.Types.ObjectId,
            ref: "users"
          }
        }
      ],
      comments: [
        {
          type: Schema.Types.ObjectId,
          ref: "comment",
          date: {
            type: Date,
            default: Date.now
          }
        }
      ],
      date: {
        type: Date,
        default: Date.now
      }
    });

module.exports = Post = mongoose.model("post", PostSchema);

这是使用ajax与php文件联系的脚本。 readProducts()是一个简单的函数,可以从数据库中获取数据。

<div class="container">
     <form class="form" id="insert-product" method="POST">
              <div class="form-group">
                  <label class="form-label" for="name">Product Title</label>
                  <input type="text" class="form-control" id="title" name="ptitle"  tabindex="1" required>
              </div>              
               <div class="form-group">
                  <label class="form-label" for="message">Product Description</label>
                  <input type="text" class="form-control" id="desc" name="description" tabindex="2" required>                               
              </div>
              <div class="form-group">
                  <label class="form-label" for="email"> Price</label>
                  <input type="text" class="form-control" id="price" name="price" tabindex="2" required>
              </div>                            
              <div class="form-group">
                  <label class="form-label" for="subject">Picture of Product</label>
                  <input type="text" class="form-control" id="subject" name="picture"  tabindex="3">
              </div>                            

              <div class="text-center">
                  <button type="submit" name="submit" class="btn btn-start-order">SAVE</button>
              </div>
          </form>
      </div>
  </div>

这是将数据插入数据库的php文件。 connect.php经过测试,可以正常工作。

   $('#insert-product').on('submit', function(event) {
           event.preventDefault();
           $.ajax({
                    url: 'insertPro.php',
                    type: 'POST',
                    data: $('#insert-product').serialize(),
                    success: function(data) {

                        readProducts();
                    }

                 });
       })

这是我的连接文件。

<?php 
require_once('connect.php');

if (!empty($_POST)) {
    $response = array();

    $query = "insert into products(id,name,description,img_file,price) values(:title, :description, :picture, :price)";
    $stmt = $DBcon->prepare( $query );

    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':description', $description);
    $stmt->bindParam(':picture', $picture);
    $stmt->bindParam(':price', $price);

    $title = $_POST["ptitle"];
    $description = $_POST["description"];
    $price = $_POST["price"];
    $picture = $_POST["picture"];

    $stmt->execute();

    if ($stmt) {
        $response['status']  = 'success';
        $response['message'] = 'Product Deleted Successfully ...';
    } else {
        $response['status']  = 'error';
        $response['message'] = 'Unable to delete product ...';
    }
}

当我按下按钮提交数据时,ajax会按应有的刷新,但记录未添加到数据库表中。

1 个答案:

答案 0 :(得分:1)

我假设id表的products列是一个自动增量列。

在这种情况下,您可以将其保留在列列表中,或者将其设置为NULL

所以

$query = "insert into products(name,description,img_file,price) 
                        values(:title, :description, :picture, :price)";

$query = "insert into products(id,name,description,img_file,price) 
                        values(NULL, :title, :description, :picture, :price)";

在此脚本的最后,您还创建了响应,但实际上从未将其发送回AJAX调用

$stmt->execute();

if ($stmt) {
    $response['status']  = 'success';
    $response['message'] = 'Product Deleted Successfully ...';
} else {
    $response['status']  = 'error';
    $response['message'] = 'Unable to delete product ...';
}
// add this line
echo $json_encode($response);

然后,您将dataType: 'JSON',添加到AJAX参数中,就可以将data中的结果作为javascritp对象处理

    $.ajax({
        url: 'insertPro.php',
        type: 'POST',
        data: $('#insert-product').serialize(),
        dataType: 'JSON',