J. Robinson J. Robinson - 4 months ago 19
PHP Question

PHP OOP: mysql_connect not returning false when wrong information passed

So i'm trying my hand in PHP OOP, and i'm trying to make a simple mysql database connect class. Here is my code and then i'll explain what's going on.

index.php

<?php

// Connect to Database Class
require_once('../libs/DB.class');
$connection = new DatabaseConnect('localhost', '', '');


DB.class

<?php

class DatabaseConnect {

// When class is called, make sure to grab the host, username, and password to connect to the MySQL Database

public function __construct($db_host, $db_username, $db_password) {
echo 'Attempting Connection . . . <br>';

// If the method Connect() doesn't return true then kill the script and say you done messed up... or tell the user that connection has been successful

if(!$this->Connect($db_host, $db_username, $db_password)) {
die("Connection to $db_host failed");
} else {
echo "Connected to $db_host";
}
}

// When the Connect method is called from the construct, grab the passed variables, try to connect, and return true or false

public function Connect($db_host, $db_username, $db_password) {
if(!mysql_connect($db_host, $db_username, $db_password)) {
return false;
} else {
return true;
}
}

}


Since i have supplied no username, and no password when making the object in the index.php file, the construct should be killing the script and saying that i have not been able to connect to mysql. However, no matter what i supply to the $db_username or $db_password variables, whether the login information is correct or not, the Connect() method is ALWAYS returning true. it never returns false, ever. Im not sure why. Any help would be appreciated.

Thanks!

Answer

mysql_connect() was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. you can use

PDO::__construct()

try {
     $dbh = new PDO($db_host, $db_username, $db_password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }

mysqli_connect()

if(!mysqli_connect($db_host, $db_username, $db_password)) {
      return false;
    } else {
      return true;
    }
Comments