[英]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_
扩展名。 开始使用mysqli
或PDO
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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.