2

所以我正在使用我在书中找到的这个功能,但它似乎不起作用。

/*
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

所以我直接在命令行上尝试了相同的查询以及反引号,它成功了。有什么建议么?

4

2 回答 2

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;
} 

这是错误的原因。

于 2013-06-13T01:28:20.460 回答
2

仔细查看您的错误消息。它告诉您WHERE在您的查询中出现两次。

从您在调用WHERE中传递给的字符串中删除它应该可以工作。$condition$a->updateRecords()

于 2013-06-13T01:28:39.183 回答