Chris Bainbridge suggested a modification to my WebCT import script which made me think... why does Moodle simply use addslashes() to escape data for database insertion?
For MySQL and Postgres at least, there exist specific functions to safely escape statements, and Chris wrote this function which bundles them up:
function anydb_escape_string($s) {
global $CFG ;
switch ($CFG->dbtype) {
case 'mysql':
$s = mysql_escape_string($s);
break;
case 'postgres7':
$s = pg_escape_string($s);
break;
default:
$s = addslashes($s);
}
return($s);
}
I presume there are benefits to using the more specific escaping functions?
Actually I borrowed that code from mod/wiki/ewikimoodlelib.php The db specific functions escape more than addslashes and can take account of the character set in use eg. check out note 2 of this
Actually, and since we are using ADODB already, IMO the "correct" way to do this is $db->qstr() or $db->Quote(). These functions put the target string inside single quotes in addition to adding slashes, so they give you something ready to be inserted into a query.
I vaguely remember some discussion with other developers around this issue in the past, but nothing more than that. Personally I 'd be very happy if this were to become "recommended".
I vaguely remember some discussion with other developers around this issue in the past, but nothing more than that. Personally I 'd be very happy if this were to become "recommended".
Slashing quotes isn't all, there's also character set encoding that might pop-up with the transition to UTF-8 - >=PHP 4.3 has deprecated mysql_escape_string() in favour of mysql_real_escape_string(), which attempts to use the current encoding for conversions.