PHP PDO更新预备语句问题

时间:2011-02-05 15:44:59

标签: php mysql pdo prepared-statement

大家好,我最近一直在尝试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对应的手册   用于正确语法的服务器版本   使用'附近'(Username ='test',密码   ='unknown',Email ='email')第1行的用户名='使用'

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:1)

  • 你的WHERE部分没有使用预备陈述

  • 使用die()不是要走的路;不要使用OR,而是检查抛出的异常。

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

  • 您的PDO似乎处于兼容模式。关闭它会更好

  • 我想查看最终查询,它通常有很多帮助

  • 这是我对同一主题的问题,希望你能发现它有用:
    Insert/update helper function using PDO

  • 然而,我把PDO放在一边,然后转回到更适合我的旧mysql。

相关问题