在CodeIgniter中,使用查询构建器更新工作正常,但在我的情况下,我必须以下列方式运行多个更新查询。
$query="";
foreach($result as $row)
{
//generate query by some procedure will look like
//UPDATE `accounts` SET `lastbal` = lastbal + 500.00 WHERE `id` = 1;
$balance=$row['balance];
$accountid=$row['acid];
//append string
$query.= "UPDATE `accounts` SET `lastbal` = lastbal + $balance WHERE `id` = $accountid";
}
所以$ query就像在循环之外
$query=UPDATE `accounts` SET `lastbal` = lastbal + 500.00 WHERE `id` = 1;
UPDATE `accounts` SET `lastbal` = lastbal + 200.00 WHERE `id` = 2;
UPDATE `accounts` SET `lastbal` = lastbal + 60.00 WHERE `id` = 3;
Excution
$this->db->query($query);
我收到的错误就像缺少参数blah ... blah
QUERY在 SQL控制台上正常运行。是否可以在批处理模式下执行此查询。
我不想以下列方式在循环内运行查询
$this->db->set('lastbal', "lastbal+$balance", FALSE);
$this->db->where('id', $acid);
$this->db->update('accounts');
我希望它在批处理模式下,其中column_old_value +输入应该可用。
答案 0 :(得分:0)
使用有效记录$this->db->update_batch()
$data = array();
foreach($result as $row)
{
$data[] = array(
'id' => $row['acid'] ,
'lastbal'=> 'accounts'.'lastbal' + $row['balance']
)
}
$this->db->update_batch('accounts', $data, 'id');
答案 1 :(得分:0)
如果您不想在循环内运行查询,则必须使用
但不幸的是,在update_batch
中,今天没有参数选项来禁用转义值,所以
在查询之前使用此行:
// set this to false so that _protect_identifiers skips escaping:
// Codeigniter 3.x.x
$this->db->protect_idenifiers(FALSE);
// Codeigniter 2.x.x
$this->db->_protect_identifiers=FALSE;
这将停止向构建的查询添加反引号。
并提供如下输入
$data = array();
foreach($result as $row)
{
$data[] = array(
'id' => $row['acid'] ,
/* Give input as string */
'lastbal'=> 'lastbal +' . $row['balance']
)
}
$this->db->update_batch('accounts', $data, 'id');
// important to set this back to TRUE or ALL of your queries from now on will be non-escaped:
// Codeigniter 2.x.x
$this->db->_protect_identifiers=TRUE;
// Codeigniter 3.x.x
$this->db->protect_idenifiers(TRUE);
请注意以上内容不会逃避您的查询
或强>
通过修改核心来尝试此操作,只要给定值为数组,它就会跳过转义,以便使用protect_identifiers转发其余查询
https://github.com/bcit-ci/CodeIgniter/blob/develop/system/database/DB_query_builder.php#L2098
功能
public function set_update_batch($key, $index = '', $escape = NULL)
{
..
..
..
}
发件人强>
'value'=>($escape === FALSE ? $v2 : $this->escape($v2))
要强>
'value'=>(is_array($v2) ? $v2[0] : ($escape === FALSE ? $v2 : $this->escape($v2)))
并提供如下输入
$data = array();
foreach($result as $row)
{
$data[] = array(
'id' => $row['acid'] ,
/* Give input as array */
'lastbal'=> array( 'lastbal +' . $row['balance'] )
)
}
$this->db->update_batch('accounts', $data, 'id');
旧CI 2.2.x
修改DB_active_rec.php
发件人强>
if ($escape === FALSE)
{
$clean[$this->_protect_identifiers($k2)] = $v2;
}
else
{
$clean[$this->_protect_identifiers($k2)] = $this->escape($v2);
}
要强>
$clean[$this->_protect_identifiers($k2)] = (is_array($v2)? $v2[0] : ( ($escape === FALSE) ? $v2 : $this->escape($v2) ));