I’m trying to migrate a lot of old PHP mysql prodecural function like mysql_query, mysql_real_escape_string etc. into PDO with minimum effort. I don’t want to rewrite every old DB function. The reason is that it’s rather an old application and I’m developing a new module into it and want to use PDO there.
So now I’m porting these old functions into PDO methods – I apended _port to my old functions so I use mysql_query_port, mysql_fetch_array_port, mysql_num_rows_port and mysql_real_escape_string_port.
The first three works pretty good:
function mysql_query_port($query) {
$db = Database::instance();
$statement = $db->prepare($query);
if (!$statement->execute())
return false;
return $statement;
}
function mysql_fetch_array_port(PDOStatement $statement) {
return $statement->fetch();
}
function mysql_num_rows_port(PDOStatement $statement) {
return $statement->rowCount();
}
The problem is with mysql_real_escape_string – I can’t use it when I don’t have mysql connection. So please help me decide what to do (or find a bug in my code):
- Init
mysql_pconnect()at the beginning of the script so that I can still usemysql_real_escape_string(I won’t be doing any queries through that connection). - Write some alternative. The manual says this function "prepends backslashes to the following characters: \x00, \n, \r, , ‘, " and \x1a.", so I came up with this:
.
function mysql_real_escape_string_port($string) {
return addcslashes ($string, "\x00\n\r\\'\"\x1a");
}
What do you think?
mysql_real_escape_stringrequires a connection because its output depends on the connection character set.If you are able to sync character sets manually (or if you never change it), you may write your own implementation.