0

I have aleady use mysqli for the main connection, but use this mysql for additioal connection on particular page.

class DBController {
private $host = "localhost";
private $user = "root";
private $password = "";
private $database = "blog_samples";

function __construct() {
    $conn = $this->connectDB();
    if(!empty($conn)) {
        $this->selectDB($conn);
    }
}

function connectDB() {
    $conn = mysql_connect($this->host,$this->user,$this->password);
    return $conn;
}

Is it good & safe enough? Are there better way for doing this? please explain me the advantage. Thanks in advance

  • 2
    It is already bad because `mysql` api is deprecated in latest php5 and removed in php7. And you __must__ forget about it and use `mysqli` or `PDO`. – u_mulder Apr 21 '17 at 06:50
  • As already said, stop using mysql and use mysqli or PDO instead. Also, you should check if the connection was successfull or not, and return some errors. Use try / catch. – Twinfriends Apr 21 '17 at 06:57

1 Answers1

0

You can use pdo method for connection and check.

try {
  $conn = new PDO('mysql:host=localhost;dbname=database_name', $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
  echo 'ERROR: ' . $e->getMessage();
}

Other method also are mysql or mysqli as per your php version.

// Try and connect to the database
$connection = mysqli_connect('localhost',$username,$password,$dbname);

// If connection was not successful, handle the error
if($connection === false) {
    // Handle error - notify administrator, log to a file, show an error screen, etc.
}
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13