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

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

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?