奇怪的pdo sql更新行为

时间:2017-05-04 14:50:26

标签: php mysql sql pdo

我在UPDATE中有一个sql PDO查询,它应该更新名称和权限字符串。 但它只是将该行的id放在所有列中。

这是我的代码:

public function saveRole($roleID, $name, $permissions)
{
    $sql = "UPDATE roles SET name = :name, permissions = :permissions WHERE id = :id";

    //this one sets a string variable in the PDO wrapper class
    PDO::setSQL($sql);

    //this one sets an array inside the PDO wrapper class
    PDO::setData([
        'name' => $name,
        'permissions' => $permissions,
        'id' => $roleID,
    ]);

    PDO::execute();

    return PDO::getResponse(true);
}

如您所见,我已经为PDO编写了一个包装器,如下所示:

static function execute($sql = null, $data = null, $fetchmode = \PDO::FETCH_OBJ)
{
            //check if data and SQL are set in function call, if so, use function call params, if not use class params ($this->SQL & $this->data)
    self::connect();

    try
    {
        $stmnt = self::$con->prepare(self::$sql);

        $stmnt->setFetchMode($fetchmode);

        if (sizeof(self::$data) > 0)
        {
            foreach (self::$data as $key => $value)
            {
                $stmnt->bindParam(':' . $key, $value);
            }
        }

        $stmnt->execute();

        self::$stmnt = $stmnt;

        self::$data = [];
        self::$sql = '';

        self::$lastResponse = new pdoReturn(true, $stmnt);

        return;
    } catch (\PDOException $exception)
    {
        self::$data = [];
        self::$sql = '';

        self::$lastResponse = new pdoReturn(false, $exception);

        return;
    }
}

function setSQL($sql) { 
    if (!is_string($sql)) 
        return false; 
    if (strlen($sql) == 0) 
        return false; 
    $this->sql = $sql; 
    return true; 
} 

function setData($data) { 
    if (!is_array($data)) 
        return false; 
    $this->data = $data;
    return true; 
}

1 个答案:

答案 0 :(得分:0)

  

如您所见,我为PDO编写了一个包装器

要立即修复,请更改

   $stmnt = self::$con->prepare(self::$sql);
   $stmnt->setFetchMode($fetchmode);

    if (sizeof(self::$data) > 0)
    {
        foreach (self::$data as $key => $value)
        {
            $stmnt->bindParam(':' . $key, $value);
        }
    }

    $stmnt->execute();

    $stmnt = self::$con->prepare(self::$sql);
    $stmnt->setFetchMode($fetchmode);
    $stmnt->execute(self::$data);

然后阅读your first database wrapper's childhood diseases并解决其他问题,例如有状态和错误报告。