Constructor failed on creating a new PDO connection - php

I'm trying to access a remote MySQL server. I created a user in the remote server and granted all the remote privileges to all hosts.
This is my code for connecting to database:
<?php
try{
$dsn = "mysql:host=MY_REMOTE_SERVER_IP;dbname=DB_NAME;port=3306";
$db = new PDO($dsn, 'USER_NAME','PASSWORD');
}catch(Exception $e){
echo $e->getMessage();
}
The code is working fine on my localhost. I even tried the code on some Playgrounds and it's working fine. But on my website, it's not working. The website does not connect to the database and always returns Constructor failed error.
The PHP version is 7.4 on my website and it supports PDO. But I don't know why it does not make the connection?
This is a picture of the error:

Just guessing: you maybe should not use the remote ip address, but localhost or 127.0.0.1 for your database host.
According to the pdo source code, this error message means the connection failed, which is not really helpful, but could mean one of these things (but not limited to):
hostname is wrong
database name is wrong
credentials are wrong
some networking issue
you name it :)
My prime suspect is the hostname, but just make sure all parameters are correct.

Related

Unable to Connect to Mysql Through PDO on Certain Networks

I am trying to connect to a MySQL database through PHP's PDO. It works fine on my home network and some other networks (coffee shops, public internet). When I try to connect through my phone's personal hotspot or through hotel wifi, it no longer works.
I am using the same login information across all of these with the same machine setup (XAMPP VM - Mac). This is my connection file:
$DBO = "mysql:host=$DB_Servername;dbname=$DB_Name";
try {
$conn = new PDO($DBO, $DB_Username, $DB_Password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection Failed: " . $e->getMessage();
}
This is the error I am getting:
Connection Failed: SQLSTATE[HY000] [2002] Connection timed out
I've tried the server name with the website address and the ip address. The strange thing is when I'm using the VS code database extension, I am able to connect to the database fine (no matter the network I am on). I can't figure out why that would be working but the PDO wouldn't be.
I read this answer about adding a space after 'mysql: ', and it returns this new message:
Connection Failed: SQLSTATE[HY000] [1045] Access denied for user 'dailyrts_realDB'#'localhost' (using password: YES)
The user account I am logging in with is assigned to the correct database and the new IP's I connect to are being registered.
dns_get_record returns:
dns_get_record(): A temporary server error occurred.
I wasn't able to find a fix using XAMPP-VM however, the same code works perfectly when using the XAMPP Installer version of the app on MacOS. I looked around for a bit to see if anyone else was having this problem and I didn't find anything that matches this issue specifically. Most were referring to connecting to a local database.
This answer about accessing MySQL through the root user is pretty close to the issue I was having and they recommend following this guide to fix the issue. I don't need to have the VM version installed so I haven't tested this myself however, it seems to have worked for him.
I'm not sure why the VM version only works on some networks and not others when connecting to MySQL databases. I'm sure this has something to do with port blocking on the network's end (mobile hotspot providers are notorious for blocking ports) and because the VM version handles network traffic differently from the regular version.
It looks like issues with the VM version are not isolated to this specific issue on MacOS. In my personal experience (and others), I'd recommend going with the installer version if you are able to. It is more developed and has more online support surrounding it.

PHP - Connect to different servers database

I'm developing on 'server1'.
I need to save the data processed on this server to the 'server1' database.
However, I also need to save some data to an external 'server2' database.
The problem is that when I connect to the database of the other server I get a fairly weird error.
Error code: 1045
Error message: Access denied for user 'server2-username'#'server1-name' (using password: YES)
Why does 'server1' appear in the error message?
To me, the message says this: "hey, I can't find the 'server2-username' on 'server1' database". Am I correct? Why does say that, when I'm connecting to 'server2'?
$connection = new mysqli('server2-ip', 'server2-username', 'server2-password', 'server2-database');
if($connection->connect_errno) {
echo $connection->connect_errno;
echo $connection->connect_error;
}
Any idea how should I connect to 'server2'? Or what should I check?
This is the first time I want to connect to another server database. I haven't done this yet, and I don't know what's wrong.
This error mean 'server2-username' try to connect from 'server1-name' and not succeed.
Please check permissions user2 on server2 for connect from remote host
It demands an account which matches the connecting user#hostname, which is server2-username#server1-name... it's just that the web-server runs on the same host server1-name as the mySQLd on server1-name. This may appear confusing, but the hostname comes from where the script runs.
You'd need to add user server2-username#server1-name to the mySQLd on server2-name... and if you can't get that account set up, most commonly there's a JSON API available as a web-service; exporting/importing data to any format would also be an option, if they wish to import themselves.
SSL tunneling could even connect through local loop-back interface 127.0.0.1 on :3307 (the problem isn't bind-address = 127.0.0.1, but that there is no such user#hostname available):
shell_exec("ssh -fNg -L 3307:server2-ip:3306 server2-username#server2-ip");
$connection = new mysqli('server2-ip', 'server2-username', 'server2-password', 'server2-database', 3307);
However, either getting that remote user account setup or using an API might rather be the suggested options, because the SSL tunnel created with shell_exec() might be closed at any time, which all needs to be tested & handled accordingly. The error message would at least be server2-username#server2-name or server2-username#localhost, when tunneling into it.

PDO statement in Azure websites with MySQL in-App

I have created a web app to communicate with MySQL In-App for Azure website.
However I'm getting error as,
"Connection failed: SQLSTATE[HY000] [2002] An attempt was made to access a socket in a way forbidden by its access permissions."
I have made sure that host, database, username and password are correct.
Don't know the issue, looks like authentication issue though.
Sample Code :
$pdocon = "mysql:host".$conStr["Data Source"].";dbname=".$conStr["Database"];
try {
$conn = new PDO($pdocon, $conStr["User ID"], $conStr["Password"]);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
Where, if I simply print $pdocon I have values.
Also, I have correct values in my $conStr array.
If you are using lower App Service Plan, you may scale to a higher App Service Plan and then check.
Check in your web app application settings if there is a connection string. PHPmyadmin uses MYSQLCONNSTR_ to connect to the MySQL server. If you have a connection string in application setting change the connection string type to Custom , so you can still have the information if needed or delete it. This will force PHPmyadmin to access MYSQLCONNSTR_localdb and connect to the MySQL in-app server.
Reference:https://blogs.msdn.microsoft.com/appserviceteam/2016/09/08/troubleshooting-faq-for-mysql-in-apppreview/
As mentioned in this document (https://github.com/projectkudu/kudu/wiki/Azure-Web-App-sandbox), Connection attempts to local addresses (e.g. localhost, 127.0.0.1) and the machine's own IP will fail, except if another process in the same sandbox has created a listening socket on the destination port.
Rejected connection attempts, such as the following example which attempts to connect to 127.0.0.1:80, will result an exception error.
Refer these FAQs (https://github.com/projectkudu/kudu/wiki/MySQL-in-app) for more details:
Where can I find MySql Credentials (connection string)?
The connection string flows to your application as an env variable MYSQLCONNSTR_localdb. Beware that we are not using the default MySql port (3306). In fact, the port number may vary for each application life cycle depending on its availability at startup time. The port info is also available as an env variable WEBSITE_MYSQL_PORT to your site.
How to use phpMyAdmin with MySql in-app?
phpMyAdmin is enabled by default with the feature. You can access it thru https://.scm.azurewebsites.net/phpMyAdmin/. Since MySql is only started with the main site, do make sure that the main site is running (simplest way is to turn on AlwaysOn) before using phpMyAdmin. Unlike phpMyAdmin from SiteExtenions gallery, this phpMyAdmin is aware of MySql credentials and will connect automatically.
Important: If you previously have phpMyAdmin installed via SiteExtension gallery, you will have to uninstall it. Since this phpMyAdmin from SiteExtension gallery will take precedent and it is notMySql In-App aware, it will not work with MySql In-App.
Maybe the values for connection string are not correct. That message is related to a bad username, password, database or server values.
Try to check this link if you are obtaining the connection values in another form. The connection string is stored under D:\home\data\mysql\MYSQLCONNSTR_localdb.txt
Another option can be related to stopped MySQL process -only for free app service plan- in such case you should run any PHP file that fires the MySQL process.

phpMyAdmin refuses MYSQL connection - How to fix it?

I'm creating a web application in PHP and I need to connect to a database and retrieve information from it. The database in question is being hosted on phpMyAdmin. I'm currently using the following PHP code to connect to it.
//Attempt to connect to the database
$conn = mysql_connect('localhost', 'my_username', 'my_password') or die (mysql_error());
//Tell the user if they were successful
echo "Connection successful!";
//Close the connection
mysql_close();
When I run the website, it produces the following SQL error:
"No connection could be made because the target machine actively refused it."
I'm sure that my username and password are spelled correctly and I believe that 'localhost' is the server name that I need to use. Is there a different mysql_connect command that I need to use for phpMyAdmin? If not, how can I solve this problem?
Edit:
Upon publishing the website to Microsoft Azure (where I need to host it), I've found that it produces a different error:
"An attempt was made to access a socket in a way forbidden by its access permissions."
How will I be able to fix this error? Or will fixing the original error also solve this one?
Do not use mysql_* functions. They are deprecated. For more information, see this question: Why shouldn't I use mysql_* functions in PHP?
phpMyAdmin hosts nothing; it is simply a PHP application that connects to your database just like your own app is attempting to do.
Take a look at the phpMyAdmin config file and ensure you are using the same host. Also try the same username/password. If this succeeds, it's advisable to set up a dedicated username/password for your application. This can be done within phpMyAdmin on the privileges page.
Try use IP instead of localhost.
User has permissions? Check them

MySQL remote access trouble?

I have a database set up on a godaddy server. It is configured to allow remote access, and there are a couple of websites I'm running which need to access this data. It works when accessed from another godaddy site, and I can connect from my development environment both at work and home. We recently set up hosting with mydomain.com.
Here is the code block that triggered it:
function connect(){
$servername = "XX.XX.XXX.XX";
$dbusername = "databaseusername";
$dbpassword = "mahpassword";
$dbname = "databasename";
try{
$newMysql = new PDO("mysql:host=".$servername.";dbname=".$dbname, $dbusername, $dbpassword);
}
catch(PDOException $e){
echo 'connection Failed: '. $e->getMessage();
die;
}
}
and now I'm getting this error message on the new site:
connection Failed: SQLSTATE[HY000] [2003] Can't connect to MySQL server on 'XX.XX.XXX.XX' (111)
The only problems I can think of is that either for some reason there are a limited number of IP addresses the MySQL database will connect to by default (which seems squirrely), I'm getting blocked by a firewall on the MySQL server (again.. doesn't make sense to me), or there is some setting on the mydomain hosting server disallowing remote requests (?)
I'm new to this kind of thing, so I'm open to any suggestions. I could probably just set up another database on the new site, but I don't want the hassle of keeping them synchronized if I don't need to. What might be wrong? Are there any workarounds?
[edit]
connected to remote database via console (mysql -h XX.XX.XXX.XX ...), the privileges were found under the information_schema database, a quick select * from SCHEMA_PRIVILEGES and select * from USER_PRIVILEGES shows that 'databaseusername'#'%' has sufficient privileges. Not that it helped me any, but maybe it'll help someone down the road.
[/edit]
As it has been more than a year since I asked this question, I suppose I need to answer it just to close it.
It turns out that godaddy had blocked mydomain.com servers via firewall ("Remote access" was limited). so in order to accomplish what I wanted to do, I had to copy and store the database on both sites.

Categories