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?
Related
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.
This question already has an answer here:
PHP: mysql_connect not returning FALSE
(1 answer)
Closed 8 years ago.
I'm very new to OOP and am trying to learn it. So please excuse my noobness. I'm trying to connect to mysql and to test whether the connection is successful or not, I'm using if-else conditions.
Surprisingly, the mysql_connect is always returning true even on passing wrong login credentials. Now I'm trying to figure out why it does and after spending about 20 minutes, I gave up. Hence, I came here to seek the help of the community. Here is my code:
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
die('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if(! $dbhandle)
{
die('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
$test = new test();
Please don't use the mysql_* functions, there are many, many reasons why - which are well documented online. They are also deprecated and due to be removed.
You'd be much better off using PDO!
Also I'd strongly advise abstracting this database code into a dedicated database class, which can be injected where necessary.
On-topic:
That code snippet seems to work for me, have you tried var_dumping $conn? Does that user have correct rights?
I also hope that you don't have a production server which allows root login without a password!
Ignoring the fact that you're using mysql_* functions rather than mysqli or pdo functions, you should utilise exceptions in OOP code rather than die(). Other than that, I can't replicate your problem - it may be that your mysql server is set up to accept passwordless logins.
class test
{
private $host = 'localhost';
private $username = 'root2'; // using wrong username on purpose
private $password = '';
private $db = 'dummy';
private $myConn;
public function __construct()
{
// returns false on failure
$conn = mysql_connect($this->host, $this->username, $this->password);
if(!$conn)
{
throw new RuntimeException('Connection failed'); // this doesn't execute
}
else
{
$this->myConn = $conn;
$dbhandle = mysql_select_db($this->db, $this->myConn);
if (!$dbhandle)
{
throw new RuntimeException('Connection successful, but database not found'); // but this gets printed instead
}
}
}
}
try {
$test = new test();
} catch (RuntimeException $ex) {
die($ex->getMessage());
}
Sorry if the title of this question does not explain the actual question. I couldn't find appropriate word to name the title of this question.
I have a database class like so:
class Database
{
private $link;
private $host, $username, $password, $database;
public function __construct($setup)
{
if ($setup == 'default') {
$this->host = 'localhost';
$this->username = 'root';
$this->password = 'root';
$this->database = 'infobox_sierraleone';
}
if ($setup == 'promo') {
$this->host = 'localhost';
$this->username = 'root';
$this->password = 'root';
$this->database = 'infobox';
}
$this->link = mysql_connect($this->host, $this->username, $this->password)
OR die("There was a problem connecting to the database.");
mysql_select_db($this->database, $this->link)
OR die("There was a problem selecting the database.");
}
public function __destruct()
{
mysql_close($this->link)
OR die("There was a problem disconnecting from the database.");
}
}
I have created to different objects of the class above in a separate file:
include 'conn/database.php';
$db = new Database('default');
$db_promo = new Database('promo');
When i run the above script, i get this message:
There was a problem disconnecting from the database.
I realise that this message if from the __destruct() function.
I have researched for some time and i am still not clear why this message is showing and how to get rid of it.
Any sort of help will be much appreciated.
Thank You.
Edit:
removed the return statement that was in the constructor.
Since you're not destroying your own objects, they get destroyed by PHP when the script is finished. PHP then just destroys anything it's got, but not necessarily in the right order.
In this case, apparently PHP kills the MySQL connection first and then continues destroying other objects, including yours. Your object then tries to disconnect the already disconnected database connection, which would go unnoticed, if you wouldn't let the script die on failure.
I have my 'dbinterface' class with a connect function. When i run this i get a statement saying "Query didn't work. No database selected"
class dbinterface {
private $_dbLink;
private $dbHost = 'host';
private $dbUser = 'user';
private $dbName = 'name';
private $dbPass = 'pass';
private $dbUserTable = 'table';
public function connect ()
{
$this->_dbLink = mysql_connect($this->_dbHost, $this->_dbUser, $this->_dbPass);
if(!$this->_dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
I made a change to the public connect function.
public function connect ()
{
$this->dbLink = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass);
mysql_select_db($this->dbUserTable);
if(!$this->dbLink)
throw new Exception ("Could not connect to database. " . mysql_error());
}
Unfortunately it output the same result. I am new to PHP and still learning, i have tried everything i know so ANY help is very much appreciated.
Unless you use an absolute schema.table type reference in your queries, you HAVE to specify a default database with mysql_select_db(). Without that,
SELECT somefield FROM sometable
fails with "no database selected" because MySQL doesn't know WHICH database it should look in for that table.
This would work, however:
SELECT somefield FROM name_of_db.name_of_table
without a default database, as you've explicitly stated you're using the "name_of_db" database.
I have an application in which I want to authenticate a user from a first database & manage other activities from another database.
I have created two classes. An object of the classes is defined in a file:
$objdb1=new db1(),$objdb2=new db2();
But when I try to call $objdb1->fn(). It searches from the $objdb2 & is showing table1 doesnot exists?
My first file database.php
class database
{
private $hostname;
private $database;
private $username;
private $password;
private $dblinkid;
function __construct()
{
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$this->hostname = "localhost";
$this->database = "aaaa";
$this->username = "xxx";
$this->password = "";
}
else
{
$this->hostname = "localhost";
$this->database = "xxx";
$this->username = "xxx";
$this->password = "xxx";
}
$this->dblinkid = $this->connect();
}
protected function connect()
{
$linkid = mysql_connect($this->hostname, $this->username, $this->password) or die("Could not Connect ".mysql_errno($linkid));
mysql_select_db($this->database, $linkid) or die("Could not select database ".mysql_errno($linkid)) ;
return $linkid;
}
Similarly second file
class database2
{
private $vhostname;
private $vdatabase;
private $vusername;
private $vpassword;
private $vdblinkid;
function __construct()
{
if($_SERVER['SERVER_NAME'] == 'localhost')
{
$this->vhostname = "xxx";
$this->vdatabase = "bbbb";
$this->vusername = "xxx";
$this->vpassword = "";
}
else
{
$this->vhostname = "localhost";
$this->vdatabase = "xxxx";
$this->vusername = "xxxx";
$this->vpassword = "xxxx";
}
$this->vdblinkid = $this->vconnect();
}
protected function vconnect()
{
$vlinkid = mysql_connect($this->vhostname, $this->vusername, $this->vpassword) or die("Could not Connect ".mysql_errno($vlinkid));
mysql_select_db($this->vdatabase, $vlinkid) or die("Could not select database ".mysql_errno($vlinkid)) ;
return $vlinkid;
}
Third file
$objdb1 = new database();
$objdb2 = new database2();
Can you help me on this?
Regards,
Pankaj
Without knowing your classes, it is difficult to help. If you are using PDO, I can guarantee you that you can create multiple instances connected to different databases without any problem. If you are using the mysql_ family of functions you probably just forgot to set the link_identifier parameter (see here).
However, having a class db1 and a class db2 sounds like a code smell to me. You probably want to have two instances of the same class with different attributes.
Each time you call mysql_connect() or the equivalent mysqli functions, if a connection already exists using those same credentials it gets reused - so anything you do to modify the state of the connection, including changing database, charsets, or other mysql session variables affects "both" connections.
Since you are using the mysql_connect() function you have the option to force a new connection each time but this is not supported on all the extensions (IIRC mysqli and PDO don't alow for this).
However IMHO this is the wrong way to solve the problem. It just becomes messy trying to keep track of what's connected where.
The right way would be to specify the database in every query:
SELECT stuff FROM aaaa.first f, aaaa.second s
WHERE f.something=s.something;
Most likely your class does not pass the appropriate connection resource to the database functions. The second argument to e.g. mysql_query() is the connection resource. Simply store this resource in an instance variable on connection, and use it every time you do something with the database.
Your problem may be in checking if the SERVER_NAME is "localhost". Seems like you may be using the same connection strings in both classes. What is $_SERVER['SERVER_NAME'] resolving to?
You're looking for the fourth parameter of mysql_connect(), which states that it shouldn't reuse existing connections:
$dbLink1 = mysql_connect($server, $user, $pass, true);
mysql_select_db($db1, $dbLink1);
$dbLink2 = mysql_connect($server, $user, $pass, true);
mysql_select_db($db2, $dbLink2);
mysql_query("SELECT * FROM table1", $dbLink1); // <-- Will work
mysql_query("SELECT * FROM table1", $dbLink2); // <-- Will fail, because table1 doesn't exists in $db2
Passing the fourth parameter as true to mysql_connect resolves the issue.
$linkid = mysql_connect($this->hostname, $this->username, $this->password,true) or die("Could not Connect ".mysql_errno($linkid));