CodeIgniter 更新和插入数据库时的进行数据转义

本文详细介绍了CodeIgniter框架中ActiveRecord模式下set方法的使用技巧及注意事项,包括如何通过设置参数来控制数据是否被转义,从而实现更灵活的数据插入与更新。

一、解决方法: 1 插入数据时,使用CodeIgniterd的Active Record模式的set方法,set()接受可选的第三个参数$escape,如果此参数被设置为FALSE,就可以阻止数据被转义,该参数的默认值是TRUE 2 更新数据时,所有的值会被自动转义,以便生成安全的查询

二、示例: 示例1: $this->db->set('name', $name); $this->db->insert('mytable');

示例2: $this->db->set('name', $name); $this->db->set('age', 'age+1'); $this->db->set('status', $status); $this->db->insert('mytable);

示例3: $array = array('name'=>$name, 'title'=>$title, 'status'=>$status); $this->db->set($array); $this->db->insert('mytable);

示例4: /* class Myclass{ var $title = 'My Title', var $content = 'My Content', var $date = 'My Date'; } */ $object = new Myclass; $this->db->set($object); $this->db->insert("mytable");

三、set方法的源码: /** * The "set" function. Allows key/value pairs to be set for inserting or updating * * @param mixed * @param string * @param boolean * @return object */ public function set($key, $value = '', $escape = TRUE) { $key = $this->_object_to_array($key);

	if ( ! is_array($key))
	{
		$key = array($key => $value);
	}

	foreach ($key as $k => $v)
	{
		if ($escape === FALSE)
		{
			$this->ar_set[$this->_protect_identifiers($k)] = $v;
		}
		else
		{
			$this->ar_set[$this->_protect_identifiers($k, FALSE, TRUE)] = $this->escape($v);
		}
	}

	return $this;
}

转载于:https://my.oschina.net/syc2013/blog/314132

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值