所以我正在使用我在书中找到的这个功能,但它似乎不起作用。
/*
Update records in the database
@param String the table
@param Array of changes field => value
@param String the condition
@return Bool
*/
public function updateRecords($table, $changes, $condition){
$update = " UPDATE " . $table . " SET ";
foreach($changes as $field => $value){
$update .= "`" . $field . "`='{$value}',";
}
//remove our trailing ,
$update = substr($update, 0, -1);
if($condition != ""){
$update .= " WHERE " . $condition;
}
$this->executeQuery($update);
return true;
}
我按如下方式实例化对象:
$a = new Mysqldb($z);
$g = $a->newConnection("localhost", "root", "secrete", "mydatabase");
并使用指定的方法如下:
$a->updateRecords("members", array("id" => 10, "username" => "Paco"), " WHERE id= 10");
但事情并没有告诉我语法错误:
Fatal error: Error executing query: UPDATE members SET `id`='10',`username`='Paco' WHERE WHERE id= 10 - 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 'WHERE id=10' at line 1 in C:\Users\Robert\Documents\web development\xampp\htdocs\xampp\web_development\MVC\registry\mysqldb.class.php on line 86
所以我在命令行上直接尝试了相同的查询以及反引号,并且它成功了。有什么建议吗?
答案 0 :(得分:5)
更改
$a->updateRecords("members", array("id" => 10, "username" => "Paco"), " WHERE id= 10");
到
$a->updateRecords("members", array("id" => 10, "username" => "Paco"), " id= 10");
两次附加WHERE
子句
您要在
中追加另一个WHERE
if($condition != ""){
$update .= " WHERE " . $condition;
}
这是错误的原因。
答案 1 :(得分:2)
仔细查看您的错误消息。它告诉您WHERE
在您的查询中出现两次。
从WHERE
来电中传递给$condition
的字符串中删除$a->updateRecords()
,它应该有效。