update where子句中的命名参数(pdo对象)

时间:2018-03-05 10:35:22

标签: php

我尝试将此查询从this thread翻译成PDO object

UPDATE table_name
   SET col1 = <<new value>>,
       col2 = <<new values>>,
       last_modified_timestamp = <<new timestamp>>
 WHERE primary_key = <<key column>>
   AND last_modified_timestamp = <<last modified timestamp you originally queried>>

所以我在mysql表中有一个“modified”字段并获取数据(SELECT modified AS last_modified)预先填写表单中的隐藏字段并将值发布到对象:

$position->readOne();    
$position->last_modified = $_POST['last_modified'];    
    <input  name='last_modified' value='{$position->last_modified}'>

我的对象更新查询如下:

UPDATE positions
SET 
... some values ...
WHERE id=:id
AND modified=:last_modified

$stmt->bindParam(":last_modified", $this->last_modified);

如果我检查发布的变量,一切看起来都很好,但更新查询完全忽略了我的第二个where子句,并在发布表单后覆盖修改后的字段。

确定是初学者问题,但我找不到。

由于

编辑: 选择查询

public function readOne(){

        $query = "SELECT 
        p.position,
        p.modified,
        p.modified AS last_modified
        FROM positions p
        WHERE id = ?
        LIMIT 0,1";

        $stmt = $this->conn->prepare( $query );
        $stmt->bindParam(1, $this->id);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

       $this->position = $row['position'];            
       $this->modified = $row['modified'];
       $this->last_modified = $row['last_modified'];

    }

更新查询

 public function updatePosition(){
        $this->getTimestamp();

        $query = "UPDATE positions
                SET 
                position=:position,
                modified=:modified,
                WHERE id=:id
                AND modified=:last_modified";

        $stmt = $this->conn->prepare($query);
        $this->position=htmlspecialchars(strip_tags($this->position));

        $stmt->bindParam(":id", $this->id); 
        $stmt->bindParam(":position", $this->position);
        $stmt->bindParam(":modified", $this->timestamp);
        $stmt->bindParam(":last_modified", $this->last_modified);

        if($stmt->execute()){
            print_r($this->last_modified);
            return true;
        }
        print_r($stmt->errorInfo());
        return false;
    }
 public function getTimestamp(){
     date_default_timezone_set('Europe/Berlin');
     $this->timestamp = date('Y-m-d H:i:s');
 }

1 个答案:

答案 0 :(得分:0)

我明白了。更新查询和其他一切工作正常,但问题是通知处理,所以函数updatePosition()告诉我所有内容都已更新但它应该工作,如果值不相同它没有更新任何东西。

这解决了它:

if($stmt->execute()){
     $affected_rows = $stmt->rowCount();
     if ($affected_rows == 1) {
          return true;
} 

这有助于我理解它是如何运作的...... PDOStatement::execute() returns true but the data is not updated