Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO not working with Port

Tags:

php

mysql

pdo

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.

like image 985
The Humble Rat Avatar asked Jan 10 '14 14:01

The Humble Rat


People also ask

Is PDO deprecated?

PDO (PHP Data Objects) Earlier versions of PHP used the MySQL extension. However, this extension was deprecated in 2012.

What's the difference between using Mysql_ functions and PDO?

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.

Does PDO use Mysqlnd?

Mysqlnd is the library/the driver to communicate with the Mysql server, both PDO and mysqli use it.

Is PDO better than MySQLi?

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.


2 Answers

You probably using localhost as a hostname. Switching it into 127.0.0.1 instead should solve the port ignorance problem.

like image 143
Slavik Meltser Avatar answered Oct 19 '22 18:10

Slavik Meltser


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.

like image 29
The Humble Rat Avatar answered Oct 19 '22 19:10

The Humble Rat