【问题标题】:PHP PDO Update prepared statement problemPHP PDO 更新准备好的语句问题
【发布时间】:2011-06-21 22:09:53
【问题描述】:

大家好,我最近一直在尝试 PDO,目前正在尝试为我正在进行的项目编写一个基本的数据库类。但是,我在尝试编写使用准备好的语句执行更新查询的函数时遇到了问题。

    function update($tabledata, $table, $where){

  $fields = array_keys($tabledata);
  $data = array_values($tabledata);
  $fieldcount = count($fields); 

  $wherefield = implode(array_keys($where));
  $whereval = implode(array_values($where));

  $this->query = "UPDATE $table SET ";
  $this->query .= '(' . implode($fields, ' = ?, ') . ' = ?)';
  $this->query .= " WHERE $wherefield = '$whereval'";

   $this->query = $this->_clean($this->query);
   $stmt = $this->conn->prepare($this->query) or die('Problem preparing query');
   $stmt->execute($data)or die('Problem executing query');

}

它的使用示例如下:

 $usertbl = 'users';
 $date = date("Y-m-d");
 $updatedata = array(
   'Username' => 'test',
   'Password' => 'unknown',
   'Email' => 'email',
   );
$where = array(
   'Username' => 'user'
    );

$Database->update($updatedata,$usertbl,$where);

这会返回以下错误:

警告:PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42000]:语法错误或 访问冲突:1064 你有一个 SQL 语法错误;检查 与您的 MySQL 对应的手册 正确语法的服务器版本 在'(用户名='测试',密码附近使用 = 'unknown', Email = 'email') WHERE Username = 'use' at line 1

任何帮助将不胜感激。

【问题讨论】:

    标签: php mysql pdo prepared-statement


    【解决方案1】:

    UPDATE 查询的 SET 子句中没有括号。

    http://dev.mysql.com/doc/refman/5.0/en/update.html

    因此,当( 被命中时会出现语法错误。只要您尝试使用绑定参数以正确的方式做事,也可以在 WHERE 子句中执行此操作!

    【讨论】:

      【解决方案2】:
      • 您的 WHERE 部分未使用准备好的语句

      • 使用 die() 不是可行的方法;不要使用 OR,而是检查抛出的异常。

      • 我很好奇,_clean()方法是做什么的?

      • 您的 PDO 似乎处于兼容模式。最好把它关掉

      • 我想看看最终的查询,通常会有很大帮助

      • 这是我关于同一主题的问题,希望对您有用:
        Insert/update helper function using PDO

      • 但是,我把PDO放在一边,转回更适合我的旧mysql。

      【讨论】:

        猜你喜欢
        • 2011-06-02
        • 2011-07-13
        • 2011-08-01
        • 1970-01-01
        • 2010-11-30
        • 2010-11-05
        • 2015-09-15
        • 2014-06-30
        相关资源
        最近更新 更多