PHP PDO Update准备的语句问题 [英] PHP PDO Update prepared statement problem

查看:92
本文介绍了PHP PDO Update准备的语句问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi everyone I've been trying my hand at PDO recently, and am currently trying to write a basic database class for a project i'm working on. However i have ran into problems trying to write a function for carrying out an update query using prepared statements.

    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的手册 正确语法的服务器版本 在'((用户名='测试',密码 ='未知',电子邮件='电子邮件')第1行的用户名='使用'

Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(Username = 'test', Password = 'unknown', Email = 'email') WHERE Username = 'use' at line 1

任何帮助将不胜感激.

推荐答案

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

There are no parentheses in the SET clause of an UPDATE query.

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

单击(时将出现语法错误.只要您尝试使用绑定参数正确执行操作,就可以在WHERE子句中执行操作!

Hence the syntax error when the ( is hit. As long as you're trying to do things the right way with bound parameters, do it in the WHERE clause too!

这篇关于PHP PDO Update准备的语句问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆