I am trying to connect to an external database using PDO.
$dbh = new PDO('mysql:host=hotsname;port=3309;dbname=dbname', 'root', 'root');
However this is not working on one particular server I have.
I thought maybe only a certain host was allowed, but I checked the mysql rules and also tried this code on a server I have personally and the connection worked.
So I know the code works and that their is no block on my side and that the firewall is accepting requests to port 3309 and passing it to the correct server on port 3306.
So the issue is solely on one server. As a test I thought I'd open port 3306 to test the code without specifying a port.
$dbh = new PDO('mysql:host=hotsname;dbname=dbname', 'root', 'root');
This worked straight away.
So my question is, why when adding the port does this cause it not to be able to connect to the database. It is only this particular server that has this issue.
Many Thanks for your time.
Update
The error given is simply "Cannot connect to mysql server on xxx.xxx.xxx.xxx".
I have gotten slightly further now. The code is now working providing I have a firewall rule to allow incoming on 3306 to the server using 3306. So even though I have specified a port, it seems to ignore this and force it to go out of 3306.
PDO (PHP Data Objects) Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.
As stated earlier, both PDO and MySQLi are extremely similar, but there's slight differences in syntax. MySQLi follows the old-school PHP snake_case convention, while PDO uses camelCase. Additionally, MySQLi's methods are used as object properties, while PDO uses the traditional syntax for functions.
Mysqlnd is the library/the driver to communicate with the Mysql server, both PDO and mysqli use it.
The main advantage of PDO over MySQLi is in the database support. PDO supports 12 different database types, in opposition to MySQLi, which supports MySQL only. When you have to switch your project to use another database, PDO makes the process simpler.
You probably using localhost
as a hostname. Switching it into 127.0.0.1
instead should solve the port ignorance problem.
The issue ended up to be due to the host. All traffic was forced out on 3306 regardless of the port specified within the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With