I'm trying to understand how datas are being handled when saving to the database in the wpdb class. I have searched for where HTML string datas are handled and found a method in the $this->query() method in the wpdb class where the query string is being stripped and thought it could be there. It's on line 1798. The $query string variable is stripped:

$stripped_query = $this->strip_invalid_text_from_query( $query );

But then I don't understand. I just can't find the stripped variable $stripped_query to be used in a query after that. The method is just returning false if it's not exactly like the original?:

if ( $stripped_query !== $query ) {
    $this->insert_id = 0;
    return false;

Why? Maybe I have misunderstood what strip_invalid_text_from_query() is doing?

Anyway.. As I said, I just wanna find the method that fixes HTML to a database safe string. So that not for example line-breaks destroys the query or so. Does anyone know where that is?

2 Answers 2


wpdb->query() is just running the query. It doesn't do anything special. And strip_invalid_text_from_query() based on the inline documentation is just stripping invalid characters in the query.

And, for your information, something like line-breaks doesn't break the database. The database can accept any string data. You just have to make sure it correctly escaped when the query runs.

Hence there is a PHP function mysql_real_escape_string. Or better using a prepared query string (see wpdb::prepare()).


There's nothing special about HTML that requires it to be treated any differently than any other kind of data being inserted. It's just text. So there isn't a specific "HTML handler" in wpdb.

Any HTML in the database still needs to be escaped though, to ensure that the query is safe from SQL injection attacks. In wpdb this is handled by the prepare() method. But it's not just HTML that need to be escaped. All user-provided values in an SQL query need to be escaped first.

$]strip_invalid_text_from_query() and strip_invalid_text() are protected methods that are only used internally by wpdb, and don't appear to have anything to do with HTML. Their purpose appears to be to remove any characters that aren't available in the database's character set.

This isn't actually used to strip the characters though. It's only used to check if there are any invalid characters by comparing the result to the original value. If characters were stripped, the operation fails. This is why $stripped_query isn't used anywhere else.

If you want to insert data into the WordPress database, and make sure it's safe, then you need to use $wpdb->prepare() or any of the other helper methods that use it internally.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.