Last edited by JP DeVries on Aug 10, 2013.


API Quick reference
Variable name: escape
Modx versions: 0.9.x + Evolution
Input parameters: (string $s)
Return if successful: MySQL escaped string $s
Return type: string
Return on failure: string $s
Object parent: DocumentParser -> DBAPI


string escape(string $s);

Escaping potential dangerous characters in a string before using it in a query can help protect your script against SQL injection attacks.

Function escapes strings passed to it in preparation for inclusion in a MySQL query. If available, this function uses mysql_real_escape_string which is binary and character set safe. If mysql_real_escape_string is not available, it will instead use mysql_escape_string to escape the data.

Usage / Examples

function login($username, $password)
   global $modx, $table_prefix;
   $username = $modx->db->escape($username);
   $password = $modx->db->escape($password);
   $res = $modx->db->select("id", $table_prefix.".modx_web_users", 
      "username='$username' AND password='".md5($password)."'");
      $_SESSION['userid'] = $id;
      //other log in things...
      //incorrect login
$string = "This is Joe's Page";
$string = $modx->db->escape($string); 

This will result in the string "This is Joe\'s Page".

select, query, [insert], update

Function Source

File: manager/includes/extenders/
Line: 117

function escape($s) {
   if (function_exists('mysql_real_escape_string') && $this->conn) {
      $s = mysql_real_escape_string($s, $this->conn);
   } else {
      $s = mysql_escape_string($s);
   return $s;

Suggest an edit to this page on GitHub (Requires GitHub account. Opens a new window/tab) or become an editor of the MODX Documentation.