MySQL Error 1045 Access Denied - php

Good Morning,
I wrote the code block below on my local Windows 7 PC and tried to run it. Unfortunately, I received:
Connect Error (1045) Access denied for user 'dbuser'#'myhost(using password: YES)
I have granted dbuser Insert, Select, Update, and Execute using both localhost and % for this database schema. I am able to mysql -u dbuser -p from command line on server as well.
Here's the code block:
<?php
/* Set Variables */
$host="serveripaddress";
$db="dbname";
$username="dbuser";
$pass="pass";
/* Attempt to connect */
$mysqli=new mysqli($host,$username,$pass,$db);
if (mysqli_connect_error()){
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
}
?>
I'm having difficulty understanding whether the above code block is causing my error, or whether there's something required to be done on the server. Can anyone suggest some areas of investigation?
Thanks,
Sid

Make sure that if you're using a hostname for the GRANT in MySQL, that MySQL can properly resolve that hostname to the IP you're connecting from.
For instance, if you do
GRANT blah ON *.* to user#somehost
you have to remember that MySQL won't see 'somehost', it'll see an IP address. It'll have to do a reverse lookup to get a hostname, and if the IP either doesn't have a reverse mapping, or maps to something completely different, MySQL won't give access.
Unless you can guarantee that the reverse mapping is stable, it's best to use IP addresses for remote access accounts in MySQL.

<?php
/* Set Variables */
$host="127.0.0.1:3306";
$db="dbname";
$username="dbuser";
$pass="pass";
/* Attempt to connect */
$mysqli=new mysqli($host,$username,$pass,$db);
if (mysqli_connect_error()){
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}
else
{
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
}
?>
First of all, add these braces in for your if/else statement. Second, try hardcoding the IP. I just ran this with an IP set to a variable (didnt work) and then I hardcoded it, worked just fine.

Related

error: Access denied for user 'root'#'localhost' (using password: NO)

I'm trying to implement a login function that allows me to extract data from facebook and save them on my moodle Website. Unfortunately, I'm not a programmer and I'm having some problems. In particular, I'm having some difficulties -I believe- related to the permission rights when I try to "write" the data extracted from fb on a MySQL database.
This is what I have done so far:
I managed to extract from Fb the data that interest me and I tried to save them to a MySQL database (created through cpannel). The code I used to access the database is basically this (with the correct parameters for my database):
// Create connection
$ Db = new mysqli ($ localhost, $ username, $ password, $ database);
// Check connection
if ($ db> connect_error) {
die ( "Connection failed:". $ db-> connect_error);
}
But when I connect to the web page I get this error: "Connection failed: Access denied for user 'root' # 'localhost' (using password: NO)"
The problem seems to be that the user/pass are incorrect. In fact, I am sure the data correspond to those included in CPannel by me at the time of database creation. The associated user has all active privileges.
I did some research and it it seemed that the problem could be associated with some "automatic" setting of Moodle. So I uninstalled moodle but nothing has changed.
I also tried to change the code:
$config = parse_ini_file('/config.ini');
// Connect to database
$mysqli = new mysqli($config['servername'], $config['username'], $config['password'], $config['dbname']);
printf("\n ".date("Y-m-d h:i:sa") . " - Establishing connection to " . $config['dbname'] . " on " . $config['servername'] . ".\n");
// Check connection
if ($mysqli->connect_error) {
die('Error : (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
printf("\n ".date("Y-m-d h:i:sa") . " - Connection failed. Returned error: " . mysqli_connect_error() . "\n");
} else {
printf("\n ".date("Y-m-d h:i:sa") . " - Connection successful.\n");
}
Unfortunately I had no luck ...
This is the tutorial i followed to implement the function:
https://www.youtube.com/watch?v=N5Kka43giyY&index=30&list=PLmpuiTmSb3xCLwwkpXeuJxwKyljf7e3Tx
I am very inexperienced, but it seems to me that the problem arises when I define password in cpannel ... it is as if the password had no value ..
Any ideas on how I can resolve it?
The problem should be related to the host parameter of the connection, review your CPanel data and try to find the host, like an IP address or domain provided by your CPanel.
You can replace $config['password'] with real password like 'your-password' in your below mysql query
$mysqli = new mysqli($config['servername'], $config['username'], 'your-password', $config['dbname']);

I need assistance with php Homework

I tried using this code to input data from a form into a database, but the code will not work and it keeps giving me access denied and error messages.I will submit my php code and a screen shot of the error messages in the hopes that you can find out why this dose not work.
Code & Screen Shot Below:
<?php
// Create connection
$con=mysqli_connect("<host>","<username>","<password>","<database>");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO usertb (username, password)
VALUES
('$_POST[username]','$_POST[password]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Access denied would point to a DB connection error. Without seeing the error message I would say its one of two possibilities, db user being denied a connection to the DB or the user not having enough rights on the DB to be able to make changes.
Confirm that you can log into the DB with the user information you have put in you code.
mysql -D 'db name' -u 'user' -p
If you can get in OK, see if your INSERT query works at the mysql command line. If it does then you know your user can enter data into that DB and you know your query is properly formed.
If the above works all OK, then you know there is something wrong with your PHP code.
Lastly I would put a positive response on your connect and query code.
$con=mysqli_connect("<host>","<username>","<password>","<database>");
// Check connection
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else {
echo "Connected to DB successfully!<br>!";
}
Hopefully that gets you a little closer.
S

Need help sorting out MySQL permissions and connections

So I'm trying to set up a PHP site that accesses and writes to a database. This should be relatively simple but I've become swamped with a mess of permission issues and I'm new to PHP so I'm not sure how to fix them all.
First off, this warning occurs when trying to access the database:
Warning: mysqli_connect(): The server requested authentication method unknown to the client [mysql_old_password]
The connection also fails due to this:
Warning: mysqli_connect(): (HY000/2054): The server requested authentication method umknown to the client
In my research I found that this warning was related to password hashing due to versioning of PHP (link)
However attempting to run the solution on that page gives me the following error:
Error Code: 1044. Access denied for user 'user'#'host' to database 'mysql'
And I don't know how to gain permissions in that database.
Here's my php code for reference (sensitive info removed):
$con=mysqli_connect("IP:port","user","password","database_name");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Succesfully connected";
echo "<br />";
}
$result = mysqli_query($con, "SELECT * FROM OWNERS") or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
echo $row['email'] . " " . $row['type'];
echo "<br />";
}
Can someone help me out with this one? I know it's a lot but it seems like all of the issues are related and I'm not sure where to start with fixing them. (I'm using XAMPP to run the php and MySQL workbench to run queries)
I suppose the mysql is running on a different machine in your network. try this to see if it works:
CREATE USER 'user'#'IP' IDENTIFIED BY 'your password';
GRANT ALL ON database_name.* TO 'user'#'IP';
if the user is already in your system but with different IP then you should create it again using the IP of your mysql server. you could also try % instead of IP in create user and grant statements but it is not recommended in production.

The mysqli_connect not working

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

Check if MySQL server is able to accept connections

What is the best way to check, from PHP, if connection to a MySQL server will succeed? I've seen some solutions that first try to open a socket connection (with fsockopen) and connect to MySQL (via whatever extension you are using) only if the socket connection was successful. I'm not too sure about this since you have to make two connections every time, does that hammer the server too much?
My problem is that if my MySQL server locks-up or stops working for whatever reason the web page just stops working (it load for a long time and then usually comes back with a 504 gateway time-out error). I'd like to display a user friendly error message if MySQL is not available. This would also, hopefully, avoid MySQL being hammered even more if it is already struggling, as new clients won't connect to it until the server comes back up.
I'm using MySQLi extension if that is relevant.
What your need is the MYSQLI_OPT_CONNECT_TIMEOUT specify in mysqli::options
details
<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
/*
* This is the "official" OO way to do it,
* BUT $connect_error was broken until PHP 5.2.9 and 5.3.0.
*/
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/*
* Use this instead of $connect_error if you need to ensure
* compatibility with PHP versions prior to 5.2.9 and 5.3.0.
*/
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . $mysqli->host_info . "\n";
$mysqli->close();
?>
From http://www.php.net/manual/en/mysqli.connect.php

Categories