Long time since I used PHP. Need to upgrade a very, very old site from mysql_*
to PDO
. The migration works well but the DB is a horrific mess of mixed Latin1
and utf8
tables. Cannot change that.
Have seen a neat solution here where you just create a connection for each type of charset, but my problem is that the site is built up as a hierarchy of classes all deriving from a single Db class, which defines the charset upon initialization.
In the old code the problem was "solved" by using mysql_set_charset()
, but unfortunetaly I cannot finde a PDO equivalence.
How to change charset on the fly on a PDO connection? Is it even possible? Or can anyone suggest a kind of pattern?
This is a "fever rescue" caused by upgrading from PHP 5.x to 7.2, and it is not an option to refactor the entire codebase nor the database.
It goes more or less like this :
class Db {
private $pdo;
public function __construct() {
$dsn = "mysql:host=".$this->hostname.";dbname=".$this->database.";charset=".$this->charset;
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
];
try {
$this->pdo = new PDO($dsn, $this->username, $this->password, $opt);
} catch(PDOException $e) {
echo "Error connecting to database: ". $e->getMessage();
}
}
}
class AnotherClass extends Db {
public function __construct() {
parent::__construct();
...
}
}
class YetAnotherClass extends AnotherClass [
...
}
Would like to implement a method on the Db
class so I in the inherited classes can execute for example $this->changeCharset('Latin1');