PHP-PDO 搜索查询然后更新结果

PHP-PDO Search query then update the result

伙计们请看下面我的代码。我真的不知道如何 运行 我的查询。我想要实现的是我将首先在我的数据库中搜索尚未完成或取消的数据 然后返回的数据将更新过期字段为 NO。 我 运行 正确地第一个查询是搜索。但我不知道如何制作第二个。请帮忙。谢谢。

<?php

require 'connection.php';

class updateOverdue{
    private $db,$sql,$stmt,$row;

    public function __construct(){
        $this->db = new connection();
        $this->db = $this->db->dbConnect();

    }
    public function updatefields(){
        $this->sql = "SELECT * FROM jrf_tbl WHERE status <> 'Finished' AND status <> 'Cancelled'";
        $this->stmt = $this->db->prepare($this->sql);
        $this->stmt->execute();

            if($this->stmt->rowCount()){
                while($this->row = $this->stmt->fetch(PDO::FETCH_OBJ)){
                 echo "
                        <tbody>
                            <tr> 
                                <td>",$TEST= $this->row->ID, "</td> 
                                <td>",$this->row->strjrfnum, "</td>
                                <td>",$this->row->strstatus,"</td>
                                <td>",$this->row->strpriority,"</td>
                                <td>",$this->row->strdate,"</td>
                                <td>",$this->row->strduedate,"</td>
                            </tr>
                        </tbody>";
                  }
            };

            foreach ($TEST as $value) { /* here is my question */
                $this->sql = "UPDATE jrf_tbl SET strifoverdue ='no' WHERE ID=". $value;
                $this->stmt = $this->db->prepare($this->sql);
                $this->stmt->execute();
            }
        }

}//End Class

?>

    <table border=1>
        <thead>
            <tr>
                <th>ID</th>
                <th>JRF Num</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Date received</th>
                <th>Due Date</th>
            </tr>
        </thead>
        <?php 
            $OverDue = new updateOverdue();
            $OverDue->updatefields();
        ?>
    </table>

您可以在单个查询中执行此操作:

UPDATE jrf_tbl SET strifoverdue ='no'
    WHERE status <> 'Finished' AND status <> 'Cancelled'"

顺便说一下,您的 $TEST 变量不是数组,因此您无法循环访问它。它只包含查询中的最后一个值。

是的,它不会给你任何结果,因为它只是更新数据库。

但是如果你真的想显示所有受影响的行,你最初的方法是可以的,但是当涉及到更新查询时,你最好使用 WHERE IN 而不是循环并在每次迭代,因为您已经在 $TEST 变量

中拥有所有 ID

$TEST 包含 id

$TEST= $this->row->ID

但你期待的是,$TEST是什么数组

foreach ($TEST as $value)

而且我认为,更好的方法是像这样编写更新查询:

UPDATE jrf_tbl SET strifoverdue ='no' 
WHERE status <> 'Finished' AND status <> 'Cancelled'