Mysqli: Unknow server host

PHP can fail to connect to a MySQL database when a custom port number is specified.
In the old-style you would write like this:
$link = mysql_connect("dbhost.info:6603", "dbuser", "dbpaswd",);

Now with mysqli the same approach does not work.
$mysqli = new mysqli("dbhost.info:6603", "dbuser", "dbpaswd", "databasename");
If you try to connect this way using mysqli, it will fail with an error Unknow server host ‘dbhost.info:6603’:

The problem is that MySQLi class does not accept the port as part of the hostname, but as a separate parameter.

Here is the correct way:
$mysqli = new mysqli("dbhost.info", "dbuser", "dbpaswd", "databasename", "6603");

The complete code sample
<?php
$mysqli = new mysqli("dbhost.info", "dbuser", "dbpaswd", "databasename", "3306");
if ($mysqli->connect_errno)
{
     print($mysqli->connect_errno);
     print($mysqli->connect_error);
}
else{print("Connected!");}
?>

Published by

MartinsM

Martins M.