du548397507 2014-11-02 19:42
浏览 89

pdo中的特殊字符

When I try to update my values it gives me the following error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined. This only occurs with special characters, for instance: (hello;) and not with (hello) For some reason it can't find values with special characters and I can only insert them and not update or remove it from my database.

And the database is already set on utf8.

public function update($data, $key, $value) {
    try { 

        $this->query = 'UPDATE ' . $this->table . ' SET ';

        array_walk($data, function($index, $key) {
            $this->query .= $key . ' = ' . ':' . $key . ', ';
        });

        $this->query = rtrim($this->query, " ,");

        $this->query .= " WHERE $key = :$value"; 

        $stmt = $this->db->prepare($this->query);

        $stmt->execute(array_merge($data, array($value => $value)));

        return true;

    } catch(PDOException $e) {
        echo $e->getMessage();
    }
}

An example how I use it:

if(isset($oldValue, $newValue)) {
$data['database']->update(array("name" => $newValue), "name", $oldValue);
}

The array is to give a key and a new value to update and after the comma is to search for the value in the table 'name'.

If someone knows a solution for this then I would be very happy, thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongshao6591 2014-11-02 20:15
    关注

    You’re parameterizing partly, and that’s good, but you should probably be parameterizing fully. To demonstrate more lucidly, let us assume we are calling update(array("occupation" => "poet"), "name", "Horace") with $this->table set to "persons". We’d then be composing this SQL:

    UPDATE persons SET occupation = :occupation WHERE name = : Horace
    

    We’d then execute it with these parameter values:

    occupation => poet
    :Horace => Horace
    

    The occupation = :occupation part is excellent and correct; but name = : Horace and :Horace => Horace is wrong. You instead should probably be composing a query like this:

    UPDATE persons SET occupation = :occupation WHERE name = :name
    

    And these parameter values:

    occupation => poet
    name => Horace
    

    If you ever have a case where you call it like update(array("occupation" => "unemployed"), "occupation", "poet"), however, you might have some issues, as you’d need to have two different parameters for occupation (one old, one new), and you’d be calling both occupation. One would win out over the other and your UPDATE would do nothing. So you’ll have to deal with that case, but otherwise, it should be fairly straightforward.

    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备