Skip to content

Instantly share code, notes, and snippets.

@dtbaker
Created July 19, 2016 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dtbaker/723b9d26fd0de3af008401d39b00f591 to your computer and use it in GitHub Desktop.
Save dtbaker/723b9d26fd0de3af008401d39b00f591 to your computer and use it in GitHub Desktop.
Upgrade from mysql_connect() to mysqli_connect() - handle port number and socket.
// These are examples of MySQL host names that will work fine in mysql_connect() but fail in mysqli_connect()
// If you are upgrading an old script to mysqli the client may have configured these as values for their database server.
// The below script parses out port number or socket and translates that into a correct mysqli_connect() call.
define('_DB_SERVER', '1.2.3.4:3306');
define('_DB_SERVER', '1.2.3.4:/tmp/socket4');
if(function_exists('mysqli_connect')){
$server = _DB_SERVER;
$port_number = null;
$socket = null;
if(preg_match('#:(\d+)$#',$server,$matches)){
$server = str_replace(':'.$matches[1], '', $server);
$port_number = $matches[1];
}
if(preg_match('#:([/\w]+)$#',$server,$matches)){
$server = str_replace(':'.$matches[1], '', $server);
$socket = $matches[1];
}
self::$dbcnx = mysqli_connect($server,_DB_USER,_DB_PASS, _DB_NAME, $port_number, $socket);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}else{
mysql_connect(_DB_SERVER,_DB_USER,_DB_PASS) or die(mysql_error());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment