繁体   English   中英

如果数据库未连接则执行功能,然后注销用户

[英]making function if database is not connect then logout user

我有以下代码用于连接数据库。 当连接有时无法连接时,我看到很多错误。 好吧,我已经把error_reporting(0);藏起来了error_reporting(0); 但我知道它不是解决方案。

db.php中

class DB {
    protected $db_name = 'demo';
    protected $db_user = 'root';
    protected $db_pass = 'root';
    protected $db_host = 'localhost';   
    public function connect() {
        $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
        mysql_select_db($this->db_name);
        return true;
    }

然后我有一个文件inc.php ,我将其包含在每一页上。

require_once 'db.php';
$db = new DB();
$db->connect();
//start the session
session_start();

现在我很困惑我在哪里包含die('Could not connect: ' . mysql_error()); 我也想header("Location: logout.php"); 如果有的话连接死了。

谢谢

我认为,如果连接和选择数据库操作成功,则connect函数返回$connection对象,如果其中任何一个失败,则返回false会更好。 然后在调用页面/函数中检查结果是否为$connection ,然后继续进行,否则进行重定向。

如下所示:

public function connect() {
    $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
    if (!($connection && mysql_select_db($this->db_name, $connection)) {
        // Log the error mysql_error()
        return false;
    } 

    return $connection;
}

在您的呼叫页面/功能中:

$connection = $db->connect();
if (!$connection) {
    header("LOCATION: logout.php"); exit();
}

// Use your $connection variable here onwards where required.

最后,请注意,不建议使用mysql_扩展名。 开始使用mysqliPDO

mysql_select_db成功返回TRUE,失败返回FALSE。

public function connect() {
    $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
    return mysql_select_db($this->db_name);
}

然后为您的inc.php

require_once 'db.php';
$db = new DB();
if (!$db->connect()) {
    header("LOCATION: logout.php"); exit();
}
//start the session
session_start();

更换:

public function connect() {
    $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
    mysql_select_db($this->db_name);
    return true;
}  

至:

public function connect() {
    $connection = mysql_connect($this->db_host, $this->db_user, $this->db_pass);
    if(!$connection){
        //die('Could not connect: ' . mysql_error());
        return false
    }if(!mysql_select_db($this->db_name)){
        return false;
    }
    return true;
}  

inc.php

require_once 'db.php';
$db = new DB();
$con = $db->connect();
if(!$con){
    header("Location:logout.php");
    exit();
}

如果未建立连接,则$ connection等于FALSE,因此:

if( $connection === FALSE ) {
    die( "Could not connect: " . mysql_error() );
}

但是,不推荐使用mysql_ *函数。 如果您正在使用现有应用程序,那么最好的选择是将所有的mysql_ *函数替换为其对应的mysqli_ *。 如果这是一个新应用程序,我强烈建议切换到PDO。 您的connect语句如下所示:

$connection = new PDO( "mysql:dbname={$this->db_name};host={$this->db_host}", $this->db_user. $this->db_pass );

如果连接失败,则会引发PDOException。 您可以在此处找到有关建立PDO连接和捕获错误的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM