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());
}
Related
I'm building a class to login users, so everything works great on localhost, but when i upload the files to the server, the code doesn't work as espected...
I checked this question Value return when no rows in PDO but i couldn't make it work...
My goal is to be able to retrieve the data from the Database and then check either the password is correct or not. I need 3 feedbacks:
User Doesn't exist
Pass/User combination doesn't match.
All good, proceed and login the user.
First I call the class:
$a = $login->login_user_admin($_POST['user']);
Then I get the result: Updated full class & connection
class Database extends PDO
{
private $dbname = "xxx";
private $host = "localhost";
private $user = "xxx";
private $pass = "xxx";
private $port = 5432;
private $dbh;
public function __construct()
{
try {
$this->dbh = parent::__construct("pgsql:host=$this->host;port=$this->port;dbname=$this->dbname;user=$this->user;password=$this->pass");
} catch(PDOException $e) {
echo $e->getMessage();
}
}
public function close_con()
{
$this->dbh = null;
}
}
class Users
{
private $con;
public function __construct()
{
$this->con = new Database();
$this->con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$this->con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function login_user_admin($user)
{
try{
$stmt = $this->con->prepare("SELECT name,salt,pass FROM users.users_admin WHERE name=? LIMIT 1");
$stmt->execute(array($user));
$this->con->close_con();
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo $e->getMessage();
}
}
}
Finally I process:
$data = [];
if ($a!=true) {
$data['success'] = false;
$data['message'] = 'User doesn't exist';
}else{
//All good proceed to chk the password.
}
I tried with empty and isset... didn't work on server either, they all work on local tough. I also try using fetchAll() and checking the empty string but i couldn't make it.
I went to check on the PHP versions on the server and local and they both running on 5.5 so I run out of ideas for now and I will appreciate some help on this.
Update!
I upload a file with only this code to check if I am getting any result from the database and I realize I am not,
include '../functions/functions.php';
$login = new Users();
$a = $login->login_user_admin("emirocast");
print_r($a);
var_dump($a);
The only user in the database right now is "emirocast" so i should get the result but i get a bool(false) instead.
The other thing I noticed is that the server is running Postgresql 8.4 and I am running 9.1 locally. Can this be the problem here?
This question already has answers here:
How to properly set up a PDO connection
(5 answers)
Closed 9 years ago.
Okay so I have some what of a dumb question, I've seen tuts and different things on making a CMS and I want to make an oop CMS, and I was wondering if someone could explain to me what the difference was between using one of the two examples?
Ex 1 -
class myClass
{
var $username;
var $password;
public function connect()
{
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $this->username,
$this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}
}
}
// Then to call that function
$obj = new myClass();
$obj->username = "root";
$obj->password = "password";
$pdo = $obj->connect();
// Then run my query down here
Ex 2 -
class database
{
protected $connection = null;
//make a connection
public function __construct($hostname,$dbname,$username,$password)
{
try {
//MySQL with PDO_MYSQL
$this->connection = new PDO("mysql:host=$hostname;dbname=$dbname",
$username, $password);
$this->connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$this->connection = null;
die($e->getMessage());
}
}
}
Or I've even seen people use a __construct then a seperate connect function
So what exactly is the difference? Is there a performance benefit by doing it a particular way? Or is there a way that is more correct than the other or are all three if these incorrect ways of doing it? I haven't found a reliable source to find an answer.
For the most cases 3rd example is the best:
In fact, PDO is already a database class. So, if you have no particular reason to create another on top of it, PDO itelf is just a perfect:
$pdo = new PDO('mysql:host=localhost;dbname=dbname', $username,$password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
is all you actually need.
There are no noticeable performance differences between the two.
The second way is preferred by a lot of people because a database object would be kind of useless if it didn't try to connect to a database. Because attempting to connect to a database is so vital to the object's worth / existence, it makes sense to send in the connection details via the constructor so that it can attempt a connection as soon as it is being instantiated. Thus, changing:
$obj = new myClass();
$obj->username = "root";
$obj->password = "password";
$pdo = $obj->connect();
to
$obj = new myClass('localhost', 'root', 'mypassword');
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'm a .Net developer that have taken over a PHP project. This project has a database layer that looks like this:
<?php
class DatabaseManager {
private static $connection;
const host = "projectname.mysql.hostname.se";
const database = "databaseName";
const username = "userName";
const password = "password";
public function __construct()
{
}
public function instance($_host = null, $_username = null, $_password = null)
{
if(!self::$connection)
{
if(!$_host || !$_username || !$_password)
{
$host = self::host;
$username = self::username;
$password = self::password;
}else{
$host = $_host;
$username = $_username;
$password = $_password;
}
self::$connection = mysql_connect($host, $username, $password);
$this->setDatabase();
}
return self::$connection;
}
public function setDatabase($_database = null)
{
if(!$_database)
{
$database = self::database;
}else{
$database = $_database;
}
$connection = $this->instance();
mysql_select_db($database, $connection) or die(mysql_error());
}
} ?>
I have written a php file that uses this layer but after a while i got these mysql errors implying i didn't close my connections which i hadn't. I try to close them but know i get other weird errors like system error: 111. Very simplyfied my php file looks like this:
<?php
$return = new stdClass();
$uid = '9999999999999';
$return->{"myUid"} = $uid;
$dm = new DatabaseManager();
$dmInstance = $dm->instance();
/* MY CLICKS */
$sql = sprintf("SELECT count(*) as myClicks FROM clicks2011, users2011 WHERE clicks2011.uid = users2011.uid AND users2011.uid = %s AND DATEDIFF(DATE(at), '%s') = 0 AND exclude = 0", mysql_real_escape_string($uid), mysql_real_escape_string($selectedDay));
$result = mysql_query($sql, $dmInstance) or die (mysql_error());
$dbResult = mysql_fetch_row($result);
$return->{"myClicks"} = $dbResult[0];
mysql_close($dmInstance);
echo json_encode($return); ?>
Okay, I'm going to post this as an answer because I think one (possibly both) of these things will help you.
First: You don't need to manually close your MySQL connections. Unless you have set them up so that they persist, they will close automatically. I would avoid doing that unless you determine that every other problem is NOT the solution.
In addition, I would switch to using prepared statements. It's more secure, and pretty future-proof. I prefer PHP's PDO over mysqli, but that's up to you.
If you'd like to look over an example of a simple PDO object to take the many lines out of creating prepared statements and connections and getting results, you can look at my homebrew solution.
Second: "System Error 111" is a MySQL error. From what I've read, it appears that this error typically occurs when you are using PHP and MySQL on the same server, but telling PHP to connect to MySQL via an IP address. Switch your $host variable to 'localhost'. It is likely that this will solve that error.
The problem here is you're calling mysql_close and not specifying a valid mysql connection resource object. You're, instead, trying to close an instance of the DatabaseManager object.
You'll probably want to run mysql_close(DatabaseManager::connection); which is where the DatabaseManager is storing the resource object.
Additionally, I'd personally recommend you learn PDO or use the mysqli drivers. In future releases of PHP the built in mysql functions will be moved into E_DEPRECATED
Try implement __destrcut
public function __destruct()
{
mysql_close(self::$connection)
}
Then simply use unset($dm);
Hey guys I have a connection class I found for pdo. I am calling the connection method on the page that the file is included on. The problem is that within functions the $conn variable is not defined even though I stated the method was public, and I was wondering if anyone had an elegant solution other then using global in every function. Any suggestions are greatly appreciated.
CONNECTION
class PDOConnectionFactory{
// receives the connection
public $con = null;
// swich database?
public $dbType = "mysql";
// connection parameters
// when it will not be necessary leaves blank only with the double quotations marks ""
public $host = "localhost";
public $user = "user";
public $senha = "password";
public $db = "database";
// arrow the persistence of the connection
public $persistent = false;
// new PDOConnectionFactory( true ) <--- persistent connection
// new PDOConnectionFactory() <--- no persistent connection
public function PDOConnectionFactory( $persistent=false ){
// it verifies the persistence of the connection
if( $persistent != false){ $this->persistent = true; }
}
public function getConnection(){
try{
// it carries through the connection
$this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha,
array( PDO::ATTR_PERSISTENT => $this->persistent ) );
// carried through successfully, it returns connected
return $this->con;
// in case that an error occurs, it returns the error;
}catch ( PDOException $ex ){ echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }
}
// close connection
public function Close(){
if( $this->con != null )
$this->con = null;
}
}
PAGE USED ON
include("includes/connection.php");
$db = new PDOConnectionFactory();
$conn = $db->getConnection();
function test(){
try{
$sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();
You can declarate database class where you carrying conn pdo class, then you don't must duplicates instaces of this. And all database operations you can doing by this class. I mean my answer is what you searching.
But i see, you using only PDO hadle class in Product Factory pattern. You can use normal full database support class under PDO (includes queryies execution from one function) and without this design pattern when you don't want to use many database connectors engines.