douzhao7014 2018-03-27 00:22
浏览 179
已采纳

使用POST将从javascript发送的数据插入到mysql数据库中

I have been trying to insert data into a table in a mysql database. This data was sent with ajax using the POST method. However, when I try to insert it into the database nothing happens.

So here is the javascript function the sends the data to the php file.

 addToCart: function(itemId,userId){
              let request = new XMLHttpRequest();
              request.open("POST", "../E-CommerceCore/addToCart.php?
              itemId="+ itemId + "?userId=" + userId, true);
              request.send();
            },

Here is where it is being used. This is nested in a bigger function so thats where the book[i].Id comes from.

   document.getElementById('add-to-cart').onclick = function(){
    cartFunctions.addToCart(book[i].Id, '1');
   };

So this takes an item id and a user id and stores them in a php variables here.

 class Cart
{
  public function addToCart($item,$user){
    include 'connect.php';
    $query = $bookStore->prepare("INSERT INTO cart SET item_Id=?, user_Id=?");
    $query->execute([$item,$user]);
  }
}

$cartManager = Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];

$cartManager->addToCart("$itemId","$userId");

This php file then runs the addToCart function which should insert it into the table. This is where I run into the problem because not data is inserted to the database when the user clicks the button. I use the connect.php file for another controller that selects from a different table in the same database, if that is an issue, and yes I have checked to make sure that the connection to the database is good. Any insight would be immensely appreciated. Please no jQuery solutions. Thank you for you time and effort.

  • 写回答

1条回答 默认 最新

  • doujiabing1228 2018-03-27 00:51
    关注

    request.open("POST", "../E-CommerceCore/addToCart.php? itemId="+ itemId + "?userId=" + userId, true); You are sending the parameters as GET with the url and you have another mistake since you used another ? to separate the 2 parameters . Please follow this link to send your data: Send POST data using XMLHttpRequest

    var http = new XMLHttpRequest();
    var url = "path_to_file.php";
    var params = "itemId="+ itemId + "&userId=" + userId; //Please note that the 2 params are separated by an **&** not a **?** as in your question
    http.open("POST", url, true);
    
    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
        }
    }
    http.send(params);
    

    Also the quotes here are unnecessary when passing parameters:

    $cartManager->addToCart("$itemId","$userId");
    

    If it is possible try to var_dump($_REQUEST) before calling the addToCart method to make sure that parameters have been successfully sent through the javascript request.

    Now regarding the sql query you have to update the class and use bindParam and afterwards call the execute. I have updated your php code as follows:

    class Cart{
      public function addToCart($item,$user){
            include 'connect.php';
            $query = $bookStore->prepare("INSERT INTO cart SET item_Id=:item_id, user_Id=:user_id");
            $query->bindParam(':item_id', $item);
            $query->bindParam(':user_id', $user);
            $query->execute();
        }
    }
    
    $cartManager = new Cart();
    $itemId = $_REQUEST["itemId"];
    $userId = $_REQUEST["userId"];
    
    $cartManager->addToCart($itemId, $userId);
    

    For more reference regarding prepared statements you can have a look at this: http://php.net/manual/en/pdo.prepared-statements.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改