Warning: mysqli::mysqli(): (28000/1045): Access denied [duplicate] - php

This question already has answers here:
MySQLI 28000/1045 Access denied for user 'root'#'localhost'
(2 answers)
Closed 6 years ago.
I noticed this has been asked several times, but I can't find an answer that works. I'm writing a class to handle my database calls, and for some reason can't establish a connection.
This is the error I received:
Warning: mysqli::mysqli(): (28000/1045): Access denied for user 'root'#'localhost' (using password: YES) in...
This is the code that attempts to create an instance of the class:
<?php
require_once 'inventoryconfig.php';
require("MySQLiClass.inc");
ini_set('display_errors',1); error_reporting(E_ALL);
echo "control";
/* works */
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database, $db_port);
if ($connection->connect_error) die($connection->connect_error);
/* doesn't */
$mysqli_db = new mysqli_db($db_hostname, $db_username, $db_password, $db_database, $db_port);
?>
Here's the class:
<?php
require_once 'IRCinventoryconfig.php';
require("drawTable.inc");
ini_set('display_errors',1); error_reporting(E_ALL);
class mysqli_db
{
protected $db_hostname;
protected $db_database;
protected $db_username;
protected $db_password;
protected $db_port;
protected $connection;
function __construct($db_hostname, $db_database, $db_username, $db_password, $db_port)
{
$this->db_hostname = $db_hostname;
$this->db_database = $db_database;
$this->db_username = $db_username;
$this->db_password = $db_password;
$this->db_port = $db_port;
if (!empty($db_hostname)
|| !empty($db_database)
|| !empty($db_username)
|| !empty($db_password)
|| !empty($db_port))
{
$this->_connect();
} else {
die("You did not provide enough information, please check your configuration files and try again.");
}
}
public function _connect()
{
/* echoes the correct information */
echo $this->db_hostname;
echo $this->db_database;
echo $this->db_username;
echo $this->db_password;
echo $this->db_port;
$this->connection = new mysqli($this->db_hostname, $this->db_username, $this->db_password, $this->db_database, $this->db_port)
or die("Database access failed:" . $this->connection->error);
//$this->connection = new mysqli($this->db_hostname, $this->db_username, $this->db_password, $this->db_database, $this->db_port);
//if ($this->connection->connect_error) die($this->connection->connect_error);
}
}

Your arguments are being provided in the incorrect order to the constructor.
$mysqli_db = new mysqli_db($db_hostname, $db_username, $db_password, $db_database, $db_port);
function __construct($db_hostname, $db_database, $db_username, $db_password, $db_port)
The constructor should probably look like this:
function __construct($db_hostname, $db_username, $db_password, $db_database, $db_port)

First all the parameters need to hold a value so:
if (!empty($db_hostname)
|| !empty($db_database)
|| !empty($db_username)
|| !empty($db_password)
|| !empty($db_port))
{
sounds wrong. I'd suggest
if (!empty($db_hostname)
&& !empty($db_database)
&& !empty($db_username)
&& !empty($db_password)
&& !empty($db_port))
{
...and the order of the parameters you pass to the construct is wrong. It must follow the mysqli construct order (host,user,pass,database,port)

That happens if you have done any custom codes (usually).when you transfer the site then it contain info of previous wordpress setup.The info don't match with the site actual login data. So after transferring site do change the info.
in my case it is in function.php
It will look like this :
$server="localhost";
$dbuser="wrdp14";
$pwd="EIzAT3vu";
$db="wrdp14";
$this->conn=new mysqli($server,$dbuser,$pwd,$db);
if ($this->conn->connect_error)
just replace it with your recent wordpress data you can find that in your wp-config file

Related

Trouble connecting to a local database using PDO [duplicate]

This question already has answers here:
PHP PDO SQLite connection
(2 answers)
Closed 1 year ago.
I have created a database using DB browser for sqlite. I would like to connect to the database using a PDO function in php. My project currently has the php dataBaseHandler file and database file in the same folder. And then the index.php file which the database is going to be used in, is in a different folder (all under the same root folder). Basically right now when using the PDO to connect to the database i am getting an error saying Connection failed: SQLSTATE[HY000] [1049] Unknown database 'jobs.db'
Here is my PDO code
<?php
class Dbh {
private $servername;
private $username;
private $password;
private $dbname;
private $charset;
public function connect() {
$this->servername = 'localhost';
$this->usernamae = 'root';
$this->password = '';
$this->dbname = 'jobs.db';
$this->charset = 'utf8mb4';
try {
$dsn = "mysql:host=".$this->servername.";dbname=".$this->dbname.";charset=".$this->charset;
$pdo = new PDO($dsn, $this->usernamae, $this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
echo "Connection failed: ".$e->getMessage();
}
$dsn = "mysql:host=".$this->servername.";dbname=".$this->dbname.";charset=".$this->charset;
$pdo = new PDO($dsn, $this->usernamae, $this->password);
return $pdo;
}
}
?>
And here is a photo of my folder structure, showing where the database file is relative to the DataBaseHandler file is.Website Structure
I should also mention that my code is being run through XAMPP.
You should use something similar to $dsn = "sqlite:" . $this->dbname; to connect to the SQLite database file.

Unable to connect PHP application with MySQL

From a friend, I got a website (zip file) with PHP and HTML files in it. I also got a SQL script from him. Now what I'm trying to do is run the application on localhost (Xampp apache server) and the website does load, but it looks like I can't connect to the database.(I did import the SQL script and it worked, But I'm still getting this error) This is an error for example that I'm receiving on the home page:
Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'dewaai'#'localhost' (using password: YES)
Notice: Undefined index: logged in C:\xampp\htdocs\deWaai\includes\header.php on line 14
The name of the database is 'dewaai'
The username is: root
And I think there is no password...
This is the connection.php file:
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "dewaai", "dewaai", "dewaai");
$db->connect();
?>
These are database functions in the db.php file:
<?php
class db {
private $conn;
private $servername;
private $dbuser;
private $dbpass;
private $dbname;
function setDB($servername, $dbuser, $dbpass, $dbname) {
$this->servername = $servername;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
}
function connect() {
try {
$this->conn = new PDO("mysql:host=$this->servername;dbname=$this->dbname", $this->dbuser, $this->dbpass);
// set the PDO error mode to exception
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
Does anyone know how I can fix this so the database runs the application?
I really don't know why I'm getting that error.
Any kind of help is appreciated, thx
There is problem with your username or password.
$db->setDB("localhost", "root", "", "dewaai");
Try this it will help you to connect with your database
Hi the issue clearly from the error message states that your username and password given in connection.php file is incorrect.
The format for DB connection is
$db->setDB( Database host IP address or DNS name , Username , Password, DatabaseName);
From what you said i guess connection.php file should be
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "root", "", "dewaai");
$db->connect();
?>
And i think your PDO connection might have an issue as well. It should be
$this->conn = new PDO('mysql:host='.$this->servername.'; dbname='.$this->dbname, $this->dbuser, $this->dbpass);
Hope this helps.

Including php file with database connection error

I want a generic php file with all the database info (dbname,host,username,password)
But when I include the page, in like index.php I get this error:
Access denied for user 'apache'#'localhost' (using password: NO)
connect.php
<?php
class dbconnect{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
function Connect($db = '**') {
if($db=='**'){
$this->host="localhost";
$this->user="**";
$this->pass="**";
$db="**";
}else{
$this->host="**";
$this->user="**";
$this->pass="**";
}
$this->con = mysql_connect($this->host,$this->user,$this->pass);
if (!$this->con)
{
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
function Disconnect() {
//$this->con = mysql_connect($this->host,$this->user,$this->pass);
mysql_close();
}
}
?>
I am sure the ** information is correct because when I specify it as:
$con=mysqli_connect("example.com","example","password","my_db");
In index.php it works
It's important to note, your test case doesn't actually prove it works.
What does this output:
$conn = mysql_connect("example.com", "user", "password");
if (!$conn) {
die('Could not connect: ' . mysql_error());
}
As you won't necessarily get the information that's failing it without that.
To top that off, let's simplify your class a little bit for debugging purposes:
class dbconnect
{
private $host = '**';
private $user = '**';
private $pass = '**';
public $con;
public function Connect($host = "localhost", $user = "root", $pass = "")
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->con = mysql_connect($this->host, $this->user, $this->pass);
if (!$this->con) {
die('Could not connect: ' . mysql_error());
}
$blaa = mysql_select_db($db, $this->con);
mysql_query("SET NAMES UTF8");
return $blaa;
}
public function Disconnect()
{
mysql_close($this->con);
}
}
Now what do you get when you do
$db = new dbconnect("example.com", "user", "password");
Be sure you're using credentials that work, and that you're not running into issues such as default values or incorrect variable assignment through these methods.
Now, if you don't want to provide the values, you can simply:
$db = new dbconnect();
Public Service Announcement
Check out PHP's PDO or at minimum (but really, just use PDO) the mysqli alternative. PHP's mysql extension is NOT secure, and you should not be using it in any environment, ever.
If the connection information are correct, check your MySQL User's host access permission:
SELECT user, host FROM mysql.user
If "localhost" is set, then the user can only access the database locally, otherwise "%" will open access.
Usually it is an issue with the connection credentials.
Check that you can log into your mysql using the details you have set for that website.
mysql -u apache -p
It will then ask you for the password.
If that login does not work, then you have a problem with that user's mysql account.
You use incorrect parameters for accessing. Just dump variables which at the line $this->con = mysql_connect($this->host,$this->user,$this->pass);. You can use debugger or echo, print instructions.
Furthermore use PDO extension for accessing to databases. It's better!
Why shouldn't I use mysql_* functions in PHP?

Handling my connection variable for login script use [duplicate]

This question already has answers here:
mysqli_query() expects parameter 1 to be mysqli, object given
(3 answers)
Closed 2 years ago.
Currently I am using
$con=mysqli_connect("x","x","x","x");
to handle my database connection on the login script. However, I'm trying to transition this to an OOP style approach such as
$con = new dbclass();
$con->openDB();`
I'm not having any luck with this though.
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 103
Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 104
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\c\login.php on line 109
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\c\login.php on line 111
Acess denied, wrong username or password?
This is the method I'm using to do this.
function openDB() {
$config = include("/assets/configs/db_config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
// 1. Create a database connection
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Can anyone make any suggestions. Do I need to use mysqli_connect() somewhere within my method. Or even better, within my db_config file :
<?php
return array("host"=>"x", "dbname"=>"x", "username"=>"x", "password"=>"x");
mysqli_report(MYSQLI_REPORT_ERROR);
?>
include() does not cause the variables defined therein to become an array - they are automatically imported into the scope in which you are calling the function. Since you are not defining $config inside the include file, you're never accessing the array.
So, $config = include('your_script.php') doesn't do what you likely think it does.
You should update the function as follows (and change the array definition inside db_config.php to define $host, $username, $password and $dbname).
function openDB()
{
include("/assets/configs/db_config.php");
$conn = mysqli_connect($host, $username, $password, $dbname);
// 1. Create a database connection
if(!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
That having been said, this isn't the best way to handle DB connections in an OOP application. If you need to move the config file, you have to update the Database class. It would be better to pass in the variables to your openDB() function as parameters, and then retrieve them from a config script in your controller somewhere.
For example, the following is much better practice:
function openDB($username, $password, $dbname, $host = 'localhost')
{
$conn = mysqli_connect($host, $username, $password, $dbname);
if(!$conn)
{
$this->error_msg = 'connection error could not connect to the database!';
return false;
}
$this->conn = $conn;
return true;
}
Try using this only initiate like $db = new db(); no need to open db it will already connect
EDIT
here is code of db_config.php
$db_host = 'localhost';
$db_user = 'root';
$db_password = '';
$db_name = 'bs_admin';
class db
{
public $dbh;
public $error;
public $error_msg;
// Create a database connection for use by all functions in this class
function __construct()
{
require(dirname(dirname(__FILE__)) . '/config/db_config.php');
if($this->dbh = mysqli_connect($db_host, $db_user, $db_password, $db_name))
{
// Set every possible option to utf-8
mysqli_query($this->dbh, 'SET NAMES "utf8"');
mysqli_query($this->dbh, 'SET CHARACTER SET "utf8"');
mysqli_query($this->dbh, 'SET character_set_results = "utf8",' .
'character_set_client = "utf8", character_set_connection = "utf8",' .
'character_set_database = "utf8", character_set_server = "utf8"');
}
else
{
// Log an error if the connection fails
$this->error = true;
$this->error_msg = 'Unable to connect to DB';
}
// Add a row to any table
public function insert($table,$field_values)
{
$query = 'INSERT INTO ' . $table . ' SET ' . $field_values;
mysqli_query($this->dbh,$query);
}
}

php/pdo/msql - access denied

There is a little pdo problem, that I have been working on for a while now. Since I don't know what is wrong here, I thought about taking it to this list. Maybe some of you know more...
I have a website with a login that checks a user and a password against a mysql driven database. When the pdo connection is made in the same file all works fine, one can log in, without any problems. Just as it is supposed to work...
However, when moving the database connection part to a seperate function, which I include from another file, pdo fails on me, and gives me:
SQLSTATE[28000] [1045] Access denied for user '...'#'...' (using
password: NO)
Fatal error: Call to a member function prepare() on a non-object in /.../.../... on line 41
For the sake of clarity, here is the code:
Version 1:
This works:
<?php
require "./vars_and_functions.php";
/* open database connection */
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
/* query */
$query = "SELECT uname, passw FROM members WHERE uname = ? AND passw = ?";
$q = $pdo->prepare($query);
$q->execute(array($u_name, $p_word_md5));
$result = $q->rowCount();
if($result == 1) { /* we have a match */
/* close the database connection */
$pdo = null;
/* and redirect */
header("...");
} /* if */
else { /* wrong credentials */
/* close the database connection */
$pdo = null;
/* and go back to the login page */
header("...");
} /* else */
} /* try */
catch(PDOException $e) {
echo $e->getMessage();
} /* catch */
?>
Here is version 2
This does not work:
<?php
require "./vars_and_functions.php";
/* open database connection */
$pdo = database_connection();
/* query */
$query = "SELECT uname, passw FROM members WHERE uname = ? AND passw = ?";
$q = $pdo->prepare($query);
$q->execute(array($u_name, $p_word_md5));
$result = $q->rowCount();
if($result == 1) { /* we have a match */
/* close the database connection */
$pdo = null;
/* and redirect */
header("...");
} /* if */
else { /* wrong credentials */
/* close the database connection */
$pdo = null;
/* and go back to the login page */
header("...");
} /* else */
} /* try */
catch(PDOException $e) {
echo $e->getMessage();
} /* catch */
?>
My includefile vars_and_functions.php looks like this:
$db_host = "...";
$db_name = "...";
$db_user = "...";
$db_pass = "...";
function database_connection() {
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
return $pdo;
}
The only real difference to my mind is that here, the pdo connection is made via a function call, whereas the function sits in the include file vars_and_functions.php.
What's wrong here?
Your function database_connection() doesn't receive the connection variables in the correct scope, so they are not set when the connection is attempted and therefore passed as NULL, and PDO defaults the connection host to localhost.
Pass them as parameters to the function:
// Defined at global scope...
$db_host = "...";
$db_name = "...";
$db_user = "...";
$db_pass = "...";
// Pass the 4 variables as parameters to the function, since they were defined at global
// scope.
function database_connection($db_host, $db_name, $db_user, $db_pass) {
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
}
// Called as:
$pdo = database_connection($db_host, $db_name, $db_user, $db_pass);
If you are only using those variables inside the connection function and don't need them elsewhere, consider defining them in scope of the function, which saves you passing them as parameters.
function database_connection() {
// Only needed here, so define in function scope
$db_host = "...";
$db_name = "...";
$db_user = "...";
$db_pass = "...";
try {
$pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass);
}
The final and often least desirable option is to define the variables at global scope as you have done, but access them via $GLOBALS[] (or the global keyword) in the function:
function database_connection() {
try {
$pdo = new PDO("mysql:host={$GLOBALS['db_host']};dbname={$GLOBALS['db_name']}", $GLOBALS['db_user'], $GLOBALS['db_pass']);
}
Note that if you are developing with error_reporting turned on and display_errors as you should be, you would see notices about undefined variables.
error_reporting(E_ALL);
ini_set('display_errors', 1);
In addition to Michael Berkowski's answer, you can also pass the global keyword like so:
function database_connection() {
global $db_host, $db_name, etc;
// your code here
}
See http://php.net/manual/en/language.variables.scope.php for more information on variable scope in PHP.

Categories