"how can i set the sql mode while using pdo?" Code Answer

2

you can use the optional 'session' variable when setting the sql_mode at runtime. that way it won't affect other clients. you can set the session sql_mode and then set it back to the previous value after your query has completed. in this way, you can set the sql_mode for a specific operation.

from the mysql manual:

"you can change the sql mode at runtime by using a set [global|session] sql_mode='modes' statement to set the sql_mode system value. setting the global variable requires the super privilege and affects the operation of all clients that connect from that time on. setting the session variable affects only the current client. any client can change its own session sql_mode value at any time."

i personally added some methods to my database class to handle this. initsqlmode() will execute the query 'select session.sql_mode' and store the default value as a class variable. setsqlmode() will allow you to set the session sql_mode to a (validated) custom value. resetsqlmode() sets the session sql_mode back to the default value. i use the session variable when manipulating the sql_mode at all times.

then you can do something like the following. note this is only psuedocode; there is nothing in my example to prevent sql injection or parameterize the sql query.

$db = new database();
$badqueryresult = $db->executestrict('bad sql query');
class database {
     ...
     function executestrict($query){
      $this->initsqlmode();
      $this->setsqlmode('strict_trans_tables,no_auto_create_user,no_engine_substitution');
      $result = $this->execute($query);
      $this->resetsqlmode();
      return $result;
     }
}
By Tonny Madsen on September 3 2022

Answers related to “how can i set the sql mode while using pdo?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.