【问题标题】:isset invocation gets last variable valueisset 调用获取最后一个变量值
【发布时间】:2023-03-10 15:19:01
【问题描述】:

我有一个名为 Question 的 PHP 类。在Question 内部是一个名为$q_id 的公共变量。

class Question{
        public $url;
        public $q_id;

        function __construct(){
            global $db;
            $this->url = $_GET["url"];


            $result = $db->query("SELECT q_id FROM wyr_questions WHERE `url` = '$this->url'");

            if ($result->num_rows == 0){
                header('Location: 404');
                die();
            }

            else{
                $row = $result->fetch_array();

                $this->q_id = $row["q_id"];

            }
        }
$user = new Question();

现在我有 2 个按钮,一个不喜欢和一个喜欢按钮。当用户按下喜欢或不喜欢按钮时,会调用$_POST 方法。 isset 方法在类之外并且在$user 对象之下。

if (isset($_POST["like"])){
        $q_id = $user->q_id;

        if ($_POST["like"] == 1){
            $db->query("UPDATE wyr_questions SET thumbs_up = thumbs_up + 1 WHERE `q_id` = '$user->q_id'"); 

        }

        else{
            $db->query("UPDATE wyr_questions SET thumbs_down = thumbs_down+1 WHERE `q_id` = '$q_id'");    

       }
}

现在,每次我点击赞按钮时,赞的数量都会根据上次的q_id 更新。例如,假设我喜欢q_id: 29,然后移至喜欢q_id: 30,那么isset($_POST["like"]) 中的查询将更新q_id: 29 而不是q_id: 30 的喜欢数量,为什么它会更新以前的q_id 和不是当前的q_id

【问题讨论】:

标签: php mysqli


【解决方案1】:

只需移动您的代码

$user = new Question();

在 isset 调用中。

类似这样的:

class Question{
    public $url;
    public $q_id;

    function __construct(){
        global $db;
        $this->url = $_GET["url"];


        $result = $db->query("SELECT q_id FROM wyr_questions WHERE `url` = '$this->url'");

        if ($result->num_rows == 0){
            header('Location: 404');
            die();
        }

        else{
            $row = $result->fetch_array();

            $this->q_id = $row["q_id"];

        }
    }

if (isset($_POST["like"])){
    $user = new Question(); //here is the new position of this code
    $q_id = $user->q_id;

    if ($_POST["like"] == 1){
        $db->query("UPDATE wyr_questions SET thumbs_up = thumbs_up + 1 WHERE `q_id` = '$user->q_id'"); 

    }

    else{
        $db->query("UPDATE wyr_questions SET thumbs_down = thumbs_down+1 WHERE `q_id` = '$q_id'");    

   }
}

【讨论】:

  • 嗯,即便如此,我仍然得到以前的 q_id 而不是当前的。
  • 你的网址内容是什么?
  • url 是我表中的列名。它会首先检查 url 是否存在,如果不存在则显示 404 错误。当我在 HTML p 标签中回显 q_id 时,会显示正确的 q_id。例如:<p><?php echo $user->q_id; ?></p>
  • 我认为这是因为您的选择查询在构造函数内..尝试将其移出
猜你喜欢
  • 1970-01-01
  • 2018-01-29
  • 2016-04-28
  • 1970-01-01
  • 2022-07-30
  • 2014-12-19
  • 2020-01-26
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多