Issue connecting to MySQL with mysqli in PHP [duplicate] - php

This question already has answers here:
Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'#'localhost' (using password: YES)
(25 answers)
Closed 6 years ago.
Been going through tons of answers but none have exactly matched my issue.
I have a MySQL database running and am attempting to connect in PHP with mysqli. The connection code is as follows:
<?php
if(!isset($_COOKIE["uid"])) {
$servername = "localhost";
$username = "study";
$password = "somepassword";
$dbname = "user_study";
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error){
die("aww");
}
}
However every time I get the error
mysqli::mysqli(): (28000/1045): Access denied for user
'study'#'localhost' (using password: YES)
I know that the user 'study'#'localhost' has permissions to access this database, because I am able to access it through the MySQL command line just fine. I have tried other accounts such as roots with the same result.
Is there anything else I should be checking?
New information (2/23)
It seems that even when I shut the database down I'm getting an access denied result, meaning it seems to be trying to connect to some other database on the server. How would I ensure it is connecting to the correct one?

I think the error message indicates that PHP was able to contact the MySQL Server using the socket file. (It would have been a different error otherwise.)
There's a couple of reasons you could get this error. If we can successfully connect to MySQL Server with a the mysql command line client like this:
> mysql --no-defaults -h localhost -u study -psomepassword user_study
That's going to rule out a lot of the possible reasons for the failure.
The most reasonable explanation for the error message from PHP is that the password being provided in the connection attempt from PHP does not match the password MySQL is expecting.
Some ideas we should be able to rule out. Privileges on the user_study database have been granted to 'study'#'localhost', e.g.
GRANT SELECT ON user_study.* TO 'user'#'localhost'
On a totally different tack, given the assignment statement:
$password = "somepassword";
And assuming that you wouldn't be supplying the actual password in the question... we're left wondering if the actual password contains characters that are subject to PHP string interpretation, such as backslash character, or a dollar sign.
For debugging, I suggest doing an echo $password; following the assignment, and verify that the string emitted is what is expected.
Another possibility is that there isn't an exact match in the mysql.user table, and the user 'study' is actually matching to a different mysql.user... an entry with an empty user ''#'localhost'.
I'd be taking a look at all of the entries in the mysql.user table where user='study' and user=''.
I also want to rule out the possibility that the mysql command line client using a .mylogin.cnf file.
I'm also tempted to suggest that changes were applied to the mysql.user table and a FLUSH PRIVILEGES statement wasn't executed... but that doesn't jive with the behavior (successful connection) observed in the mysql command line client.
We're assuming obviously that the MySQL Server is running local, on the same machine that PHP is executing on. And we're expecting to connect via the local socket file.
As a test, I'd suggest connecting via TCP. Specifying host as 127.0.0.1. That would require a different entry in the mysql.user table. We'd test connection from the mysql command line client:
> mysql --no-defaults -h 127.0.0.1 -u study -psomepassword user_study
But this gets into a whole host of other configuration issues with the MySQL Server, networking enabled, bind address, DNS name resolution, listening port, iptables, firewall, et al.
--
If the problem was an unsupported authentication protocol, I'd expect a different error. If the problem was the inability to connect to the socket file, I'd also expect a different error.
All of the usual causes for this error seem to be ruled out by a successful connection from the command line client, running on the local machine, connecting to using the same credentials.

Related

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.

MySQLi ignores host parameter

This is my setup (the IP numbers are fictional of course):
Server A (10.0.0.1)
hosts a database called database1 with the user db_user and the password db_pass. This user has access to the database and remote connections from any host are permitted (I know it's a leak and I will fix it once it works)
Update 1: This server shows no signs of receiving the connection (like connection refused or something like that) Port 3306 is open
Server B (20.0.20.0)
hosts a PHP script which connects to the database with the following command:
$connection = mysqli_connect("10.0.0.1","db_user","db_pass","database1",3306);
My log on Server B says:
Access denied for user 'db_user'#'20.0.20.0' (using password: YES) in <path-to-php-file> in line 42
The line number matches the statement, so it is indeed the statement above which fails.
Why? I explicitly specified the IP of Server A (also tried server-a.com instead of 10.0.0.1)
Update 2:
I ran the following query via commandline as MySQL-Root and this is the output:
mysql> SHOW GRANTS FOR 'db_user';
GRANT USAGE ON *.* TO 'db_user'#'%' IDENTIFIED BY PASSWORD '<password hash>'
GRANT ALL PRIVILEGES ON `database1`.* TO 'db_user1'#'%'
Seems valid to me. What strikes me as odd is that in the log of B it shows it own address (B's address) instead of A's where the Database is located. My idea is it tries to connect to a database on server B where no MySQL user db_user exists.
Update 3:
I connected via SSH to server B and ran mysql --host=10.0.0.1 -udb_user -p and typed in the password => it worked. SHOW GRANTS FOR current_user; returned the same like on server A.
If you can't connect using mysqli, try using PDO instead. I'm not sure why, but apparently in this case PDO works.
Personally, I like PDO better than mysqli, because of named parameters instead of ?, and the ability to provide an array of values when calling PDOStatement::execute(). You may find you like it as well.

Cannot connect to MySQL database on remote server using php mysqli

I am trying to use mysqli to insert some data into a MySQL database (let's call the schema myDatabase), but cannot successfully connect. Here's the code snippet to connect:
...
$config = parse_ini_file('../includes/config.ini');
$username = $config['username'];
$password = $config['password'];
$dbname = $config['dbname'];
$server = $config['server'];
$conn = new mysqli($server, $username, $password, $dbname);
if (!$conn || $conn->connect_error) {
die( 'Connection Failed: ('.$conn->connect_errno.') '.$conn->connect_error);
}
...
I get the following result:
Connection Failed: (1045) Access denied for user 'myUser'#'my.laptop.ip.address' (using password: YES)
Here's some details on the set-up, in case they are relevant:
The code is on my laptop running Windows 7 and using PHP 5.3.5 that came with xammpp.
The database is hosted on a remote server with MySQL5.1.52. I created a user to which I granted all privileges on myDatabase.*. No host was specified for the user (e.g. 'myUser'#'%'), as I am still in development and don't know the ip address where the code for the live application will be hosted.
If I ssh onto the database server, I can connect to mysql using the credentials for myUser and access the tables in myDatabase. I have another schema on this same server which is accessed by a different user, and have been able to use mysqli to connect without any problems.
Just to be sure it wasn't a typo, I dropped the user, and created it again, copying and pasting the username and password from the config.ini file used in my php code (and flushed privileges, of course). I did this again, except this time the host was specified, e.g. CREATE USER 'myUser'#'my.laptop.ip.address' IDENTIFIED BY 'myPassword'. I keep getting the same error and now I'm completely stumped.
Help, please.
On your mysql machine hit:
GRANT ALL PRIVILEGES ON database.* TO 'myUser'#'%' IDENTIFIED BY 'newpassword';
FLUSH PRIVILEGES;
This will allow the user to connect from any host. Once it works, you can limit it to just a specific host and database.
Okay, this is strange, but it appears the problem had to do with the password I was using. The original one contained some special characters ($, & +). When I changed it so that it only contained numbers, letters and underscore, it worked.
Is this real, or did I accidentally do something else without realizing that turned out to be the actual solution?

Not able to connect to database [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to connect to the database mysql?
I was trying PHP web crawler for website http://astellar.com
I did everything step by step and also create user and database for MySQL. Then connect to database with user as well but it show me an error.
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'switsolu_kll'#'localhost' (using password: YES) in /home/switsolu/public_html/crawler/_db.php on line 43
Cannot connect to database server (Reason: Access denied for user 'switsolu_kll'#'localhost' (using password: YES))
where I am wrong in there?
This error almost always appears when the MySQL password is wrong. Check, double check and then triple check that it is correct.
Often when you created user you did not declare the proper hostname or the request is coming from a host other than 'localhost'. You can create the user for wildcard for all hosts, but sometimes the order of rules messes it up.
delete user and recreate
GRANT ALL PRIVILEGES ON switsolu_aaa.* TO 'switsolu_kll'#'localhost' IDENTIFIED BY 'abc123abc';
don't forget to flush privileges
FLUSH PRIVILEGES;
And depending on your app, you may need to restart it or the server to reset socket connection and retry but shouldn't have to, just retry.
If the localhost doesn't work, then delete user and recreate with 'switsolu_kll'#'%' instead. Don't forget flush privileges; after creating user.
Check User Permission. If you running local, and still have root try:
<?php
$localhost = "localhost";
$mysqlusername = "root";
$mysqlpassword = "";
?>

Access remote database MySQL via PHP

I have a MySQL database set up on 000webhost.com. I want to access the data in my database via PHP. I tried:
<?php
include("connect.php");
mysql_select_db("XXXXXXX_users", $con) or die(mysql_error());
$result = mysql_query("SELECT * FROM data ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$user = $row['usrname'];
}
echo "$user";
?>
But it always returns as: "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."
What do I do?
I do not have root access
I'm trying to run the script on Apache
When debugging this sort of thing, it's always good to make sure you can connect using the command line mysql tool first, to rule out issues related to PHP itself.
$ mysql -u myuser -h mysql.example.com -p
You'll get a more descriptive error message as well, e.g. ERROR 1045 (28000): Access denied for user 'root'#'remote.example.com' (using password: YES)
If the mysql port is even open on a public interface to begin with (which is usually a terrible idea), mysql itself has its own layer of access control based on the connecting host. You may need to have an account created specifically with a wildcard hostname, like so:
CREATE USER 'myuser'#'%' IDENTIFIED BY 'mypassword';
The #'%' part, specifically, allows connection from any host, local or remote.
Once you can successfully connect from the command line, it's then a simple issue of replicating your command line arguments as arguments to mysql_connect()
A lot(if not all?) of hosting providers restrict remote access to the mysql database. Meaning that you can only connect via localhost. There is probably a mysql config section on the hosting provider that will allow you to config an ip address from which a certain user can connect from. Good luck.
Most of hosts doesn't provide a remote a access to MySQL server's as it a security risk, may you should try another free MySQL server's that allow remote access, try this but its a bit slow.

Categories