phpmysqlcodeigniteraddslashesutf8mb4

What is the Simple and Efficient way to handle single quotes and double quotes insertion issue using php and MySql


I am mostly working with Php 5.4+ and MySql 5.5+ versions. I am using Codeigniter for all the projects.

The problem i am facing is

Sometimes(on some production servers) when ever a POST variable contains ' or " quotes, a Database error occurs. But few times(on other servers) they work properly, i mean the quotations get inserted into tables

Though php and CI have a good facility for handling these strings with addslashes and mysql_escape_sequence etc

  1. It is not that easy to check these conditions for every possible variable that is being posted by the User

  2. Every time we have to use addslashes Ex: It\'s and while giving the output we have to again apply stripslashes to output It's. But it is difficult to handle for large values.

  3. As the Database saves the data as It\'s it is difficult to search for these strings.

For struggling for days, i found that using utf8mb4_general_ci advantageous over utf8

Accordingly i made sure the CI's Database.php have the following

    $db['default']['char_set'] = 'utf8mb4';
    $db['default']['dbcollat'] = 'utf8mb4_unicode_ci';

Also i changed the datatype for respective columns to "LONGTEXT" and its collation to "utf8mb4_general_ci"

To my surprise they worked for some servers.

But Still on some servers i found the same problem. which is bit frustrating even though i made sure the server configuration matches with those working servers.

How all php and mysql developers are working with this Scenario? what precautions are you taking?

Please suggest!!


Solution

  • On my old projects, I just have a function DB::esc() that wraps whatever escape function goes to the library I'm using, be it mysql_real_escape_string or whatever else.

    On my new projects, I use prepared statements and let the extension handle it.