做得好吗?够安全吗?为特定页面建立附加连接

时间:2017-04-21 06:47:06

标签: php mysql mysqli

我主要使用mysqli作为主连接,但是在特定页面上使用这个mysql进行附加连接。

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;
}

这是好事吗?够安全吗?这样做有更好的方法吗?请解释一下我的优势。提前致谢

1 个答案:

答案 0 :(得分:0)

您可以使用pdo方法进行连接并检查。

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();
}

根据您的php版本,其他方法也是mysqlmysqli

// 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.
}