更新时如何获取数据库中的上一条记录?

时间:2019-02-25 01:48:16

标签: php ajax pdo

我有这段历史,我应该把自己更改的内容和更改的数据放进去。 例如:我将苹果更新为芒果。在我的历史中,应该将苹果更新为芒果。我尝试了fetchColumn,但提示未捕获错误:调用成员函数fetchColumn()。这是我的代码:

    if($_POST["operationproducts"] == "Edit")
 {
  $image = '';
  if($_FILES["image"]["name"] != '')
  {
   $image = upload_image();
  }
  else
  {
   $image = $_POST["hidden_image"];
  }
    //get previous name 
    $q= $connection->query("SELECT name FROM products WHERE prodID = :prodID");
     $previousname = $q->fetchColumn();
  $statement = $connection->prepare(
   "UPDATE products 
   SET categoryID = :categoryID, brandID = :brandID, name = :name, size = :size, image = :image, price = :price, stocks = :stocks, availability = :availability, description = :description
   WHERE prodID = :prodID
   "
  );
  $result = $statement->execute(
   array(
    ':categoryID' => $_POST["categoryID"],
    ':brandID' => $_POST["brandID"],
    ':name' => $_POST["name"],
    ':size' => $_POST["size"],
    ':image'  => $image,
    ':price' => $_POST["price"],
    ':stocks' => $_POST["stocks"],
    ':availability' => $_POST["availability"],
    ':description' => $_POST["description"],
    ':prodID'   => $_POST["prodID"]
   )
  );
  if(!empty($result))
  {
    //insert to product history
    $userid = $_SESSION['userid'];
    $previous = $previousname;
    $date = date("Y-m-d H:i:s");
    $action = 'Updated ' . $previous . 'to ' . $_POST["name"];
    $remarks = $_POST["remarks"];
    $statement = $connection->prepare("
               INSERT INTO producthistory (userid, prodID, action, time, remarks) 
               VALUES (:userid, :prodID, :action, :time, :remarks)
              ");

    $result = $statement->execute(
               array(
                ':userid' => $userid,
                ':prodID' => $_POST["prodID"],
                ':action' => $action,
                ':time' => $date,
                ':remarks'  => $remarks,
               )
    );
    echo 'Data Updated';
  }
     }

 }

1 个答案:

答案 0 :(得分:0)

您错过了一个参数:prodID。

更好地使用prepare语句并将param绑定到缺少的语句

$q->bindParam(':prodID', $prodID) or using array as your way

如果您将查询用作波纹管

$q= $connection->query("SELECT name FROM products WHERE prodID = :prodID");
$previousname = $q->fetchColumn();

应替换$ previousname = $ q-> fetchColumn(); $ previousname = $ q [0] ['name'];

或者更好地转储查询结果以查看结构!