expressionengine使用数据库类编写查询

时间:2012-03-24 18:37:43

标签: expressionengine

如何在expressionengine插件中重写此查询部分

$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
    if ($key != $id_field) {
        $query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
    }
} 
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE {$id_field}={$newid}";
mysql_query($query);

我尝试了以下操作,但它在第一行显示错误;错误

$query = $this->EE->db->query("UPDATE exp_channel_titles SET ";
foreach ($original_record1 as $key => $value) {
    if ($key != $id_field) {
        $query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
    }
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= "WHERE entry_id={$newid}");
mysql_query($query); // Is this needed or should i remove it.

1 个答案:

答案 0 :(得分:2)

使用EE内置函数(更简单,更易于阅读):

$this->EE =& get_instance();

$query = array();
foreach ($original_record as $key => $value) {
    if ($key != $id_field) {
        $query[$key] = str_replace('"','\"',$value);
    }
} 
$this->EE->db->where('entry_id', $newid);
$this->EE->db->update($table, $query);

但要解释为什么你的代码不起作用;

$this->EE->db->query

这是一个运行查询的EE函数,因此在将查询传递给它之前,需要将查询构建为字符串。所以...

$query = "UPDATE exp_channel_titles SET ";
foreach ($original_record1 as $key => $value) {
    if ($key != $id_field) {
        $query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
    }
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query = " WHERE entry_id={$newid}";
$queryResults = $this->EE->db->query($query);