雷林鹏分享:CodeIgniter 转义查询

  CodeIgniter 框架提供了 Active Record 模式来对数据库进行操作,自己也比较喜欢这种操作数据库的方式,因为通过这种方式进行数据库操作系统会自动对数据进行转义过滤,可以帮助我们进行安全的数据库操作。

  但是Active Record 在数据查询方面个人觉得反而没有直接自己书写SQL语句来得方便,不好的就是使用自己的SQL语句进行查询系统默认没有对数据进行一些安全方面的操作,需要我们自己手动去进行一些安全过滤操作,这时我们就需要使用到转义查询。

  将数据转义以后提交到你的数据库是非常好的安全做法,CodeIgniter 提供了 3 个函数帮助你完成这个工作。

  1、$this->db->escape() 这个函数将会确定数据类型,以便仅对字符串类型数据进行转义。并且,它也会自动把数据用单引号括起来,所以你不必手动添加单引号

  用法如下:

  $sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";

  查看函数源码:

  function escape($str)

  {

  if (is_string($str))

  {

  $str = "'".$this->escape_str($str)."'";

  }

  elseif (is_bool($str))

  {

  $str = ($str === FALSE) ? 0 : 1;

  }

  elseif (is_null($str))

  {

  $str = 'NULL';

  }

  return $str;

  }

  2、$this->db->escape_str() 此函数将忽略数据类型对传入数据进行转义。更多时候你将使用上面的函数而不是这个。

  这个函数的使用方法是:

  $sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";

  查看函数源码:

  /**

  * Escape String

  *

  * @access public

  * @param string

  * @param bool whether or not the string will be used in a LIKE condition

  * @return string

  */

  function escape_str($str, $like = FALSE)

  {

  if (is_array($str))

  {

  foreach ($str as $key => $val)

  {

  $str[$key] = $this->escape_str($val, $like);

  }

  return $str;

  }

  if (function_exists('mysql_real_escape_string') AND is_resource($this->conn_id))

  {

  $str = mysql_real_escape_string($str, $this->conn_id);

  }

  elseif (function_exists('mysql_escape_string'))

  {

  $str = mysql_escape_string($str);

  }

  else

  {

  $str = addslashes($str);

  }

  // escape LIKE condition wildcards

  if ($like === TRUE)

  {

  $str = str_replace(array('%', '_'), array('\\%', '\\_'), $str);

  }

  return $str;

  }

  3、$this->db->escape_like_str() This method should be used when strings are to be used in LIKE conditions so that LIKE wildcards ('%', '_') in the string are also properly escaped.

  使用示例:

  $search = '20% raise';

  $sql = "SELECT id FROM table WHERE column LIKE '%".$this->db->escape_like_str($search)."%'";

  查看源码:

  function escape_like_str($str)

  {

  return $this->escape_str($str, TRUE);

  }

  我们可以看到,第一种和第三种方法其实都是调用了第二种方法。

  文章转载自 [http://www.php230.com](编辑:雷林鹏 来源:网络 侵删)

猜你喜欢

转载自www.cnblogs.com/linpeng1/p/10869099.html