Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO connection to MySQL fails, mysql_connect works fine

Tags:

php

mysql

pdo

I'm trying to connect to remote MySQL database using PDO, but it fails with error:

Connection failed: SQLSTATE[28000] [1045] Access denied for user 'my_user'@'some.ip.address' (using password: YES)

This is how I'm trying to connect:

$dsn = "mysql:host=sql.my_domain.nazwa.pl;dbname=my_db;port:3307";
$user = "my_user";
$password = "my_password";

try {
    $this->db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

and it fails. But this way:

mysql_connect('sql.my_domain.nazwa.pl:3307', 'my_user', 'my_password');

works fine.

Anyone have any idea what can be wrong with PDO, its configuration, parameters I set or maybe this specific server (nazwa.pl)?

[SOLVED] Ok, so that was simple (but also tricky to notice...) syntax error, it should be a = instead of : in port part of dsn.

like image 210
zelazowy Avatar asked Aug 03 '12 11:08

zelazowy


People also ask

Does PDO work with MySQL?

PDO will work on 12 different database systems, whereas MySQLi will only work with MySQL databases. So, if you have to switch your project to use another database, PDO makes the process easy. You only have to change the connection string and a few queries.

How do you connect to a MySQL database using PDO?

A PDO database connection requires you to create a new PDO object with a Data Source Name (DSN), Username, and Password. The DSN defines the type of database, the name of the database, and any other information related to the database if required. These are the variables and values we stated inside the dbconfig.

What is use of Mysql_connect in PHP?

mysql_connect() Function: The mysql_connect() function is used to establish a new connection with the database. This connection is established when the script starts its execution. After establishing this connection with the database, it will be valid or be connected with the database only until the script is executed.

Can I use PDO and MySQLi together?

Yes, it is possible.


2 Answers

Try replacing:

$dsn = "mysql:host=sql.my_domain.nazwa.pl;dbname=my_db;port:3307";

with

$dsn = "mysql:host=sql.my_domain.nazwa.pl;dbname=my_db; port=3307";
like image 176
Fluffeh Avatar answered Oct 23 '22 04:10

Fluffeh


If you are trying to connect to database on some other server Make sure your Sql server gives you the access on the particular port in your case 3307 from the IP address of the places where your codes are hosted. If the both the servers are same try with localhost or 127.0.0.1

like image 35
Ashish Avatar answered Oct 23 '22 03:10

Ashish