Wordpress MySQLi Revisited
I was getting this rather annoying bug ever since I updated to Wordpress 2.7 where all the newlines in my entries would be replaced with "rn". It's obviously some error related to adding and stripping slashes, but when I Googled around for it I only found one report of the same error with no answer. So I just edited all of my posts directly in the db after publishing them to fix it. Well, I'm a PHP developer professionally, so if no one else was going to solve the problem, I figured I'd do it myself. Here's the issue:
- I'm using PHP 5, my host only provides the mysqli connector in PHP 5, so I'm using a custom db.php file I got off the internet (see previous post) and modified.
- That class has a method called "escape" which calls
mysqli_real_escape_string
. This does more than addslashes does, it also replaces newlines and carriage returns with \n and \r. - That should be fine, except that Wordpress calls
$wpdb->escape( ... )
directly in a few places, and callsstripslashes
,stripslashes_deep
, andaddslashes
in several places, converting the text multiple times before it finally gets to the database. - So at one point the carriage return + newline becomes \r\n, then stripslashes turns it into rn, and addslashes won't see any need to put it back later. Hence my problem.
The solution was to have the db.php escape method simply call addslashes, as Wordpress expects, and to use str_replace
just before executing any SQL statement to finish what mysqli_real_escape_string
is supposed to do, according to the documentation.
So, in case anyone needs it, here is the updated db.php file.