3

When logging into mysql in my terminal, everything works expected. But when I run my webpage with

$conn = new mysqli("localhost", "root", "password");
if($conn->connect_error) {
   die("connection failed: " . $conn->connect_error);
}
echo "connected successfully";

I get "connection failed: Access denied for user 'root'@'localhost' (using password: YES)". I have tried resetting the root password. I have tried granting all permissions to root. I am absolutely positive that I am entering my username and password correctly in the php file.

I'm running a LAMP server on an Ubuntu 14.04 machine. I have php 5.5.9, mysql 5.5.40, and apache 2.4.7.

Can anyone help?

2
  • 1
    what happens if you try 127.0.0.1 or the machine's local IP address ex, 192.168.1.25 instead of localhost? Commented Dec 29, 2014 at 8:45
  • add database name which you are trying to connect in 4th parameter $conn = new mysqli("localhost", "root", "password","DB_NAME"); Commented Dec 29, 2014 at 8:49

2 Answers 2

2

PHP requires you to fill in the username, password and database name for the database you are trying to connect to: http://php.net/manual/en/function.mysql-connect.php

$conn = new mysqli("localhost", "root", "password", "database");
Sign up to request clarification or add additional context in comments.

6 Comments

I've tried this; it still doesn't work. I get the same results.
Are you sure the database is hosted on the same server as the webserver? Try filling in the IP you use when logging in through the terminal in the PHP file, instead of localhost.. Make sure you also use the code above with the database name
I'm doing all of this locally. I have everything installed and running from the same machine. I just got a mechanical keyboard and I'm just doing some web stuff for fun.
Ah okay, did you restart MySQL after resetting/changing your password?
Yes. I ran sudo service mysql restart
|
0

Try mysqli_connect_errno()

$conn = new mysqli("localhost", "root", "password");
if(mysqli_connect_error()) {
   die("connection failed: " . mysqli_connect_error());
}
echo "connected successfully";

Checkout Manual:

connect_error

Warning The mysqli->connect_error property only works properly as of PHP versions 5.2.9 and 5.3.0. Use the mysqli_connect_error() function if compatibility with earlier PHP versions is required.

1 Comment

This produces the same results as my original code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.