php 单击按钮时将值插入数据库

x8diyxa7  于 2023-05-16  发布在  PHP
关注(0)|答案(1)|浏览(88)

当我点击添加到收藏夹时,它添加了user_id和golf_id,但是'golf_price'一直输入为'0'而不是实际价格。任何帮助将不胜感激?

public function isFavourite($golf_id){
    $query = "SELECT * FROM user_favourites WHERE user_id = :user_id AND golf_id = :golf_id";
    $stmt = $this->Conn->prepare($query);
    $stmt->execute([
        "user_id" => $_SESSION['user_data']['user_id'],
        "golf_id" => $golf_id
    ]);
    return $stmt->fetch(PDO::FETCH_ASSOC);
}
public function toggleFavourite($golf_id){
    // Check if club is already in basket
    $is_favourite = $this->isFavourite($golf_id);

    if($is_favourite) {
        // Is already favourite - so remove. 
        $query = "DELETE FROM user_favourites WHERE user_fav_id = :user_fav_id";
        $stmt = $this->Conn->prepare($query);
        $stmt->execute([
            "user_fav_id" => $is_favourite['user_fav_id']
        ]);
        return false; // Return false for "removed"
    } else {
        // Is not favourite - so add
        $query = "INSERT INTO user_favourites (user_id, golf_id, golf_price) VALUES (:user_id, :golf_id, :golf_price)";
        $stmt = $this->Conn->prepare($query);
        $golf_price = "SELECT golf_price FROM products WHERE golf_id = :golf_id";
        return $stmt->execute(array(
            "user_id"=> $_SESSION['user_data']['user_id'],
            "golf_id" => $golf_id,
            "golf_price" => $golf_price
        ));
        return true; // Return false for "added"
        //1.use golf_id to select from products to get golf_price where golf_id matches
    }
}
esyap4oy

esyap4oy1#

你从来没有在$golf_price中执行查询,你试图将golf_price设置为那个文字字符串。因为它不是数字,所以它被转换为0
您应该将SELECT查询放入INSERT查询中。

// Is not favourite - so add
        $query = "INSERT INTO user_favourites (user_id, golf_id, golf_price)
                  SELECT :user_id, golf_id, golf_price
                  FROM products WHERE golf_id = :golf_id";
        $stmt = $this->Conn->prepare($query);
        return $stmt->execute(array(
            "user_id"=> $_SESSION['user_data']['user_id'],
            "golf_id" => $golf_id
        ));

相关问题