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

一、解决方法:
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;
}

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

上一篇:几种数据库如何读取前N条记录


下一篇:linux重新增加硬盘容量