为什么这个PHP connect_error无法正常工作?

时间:2016-10-24 07:26:53

标签: php mysql exception-handling

主要问题:

如果没有连接到MySQL服务器,我试图在网页上打印错误。为此,我写了一个错误的数据库名$this->dbname = 'dbinds';(实际是 dbind )。但是 die 语句没有执行。当我打开页面时,它根本无法加载。它显示错误: localhost页面无效。 我做错了吗?

另一个问题: 我已经评论了异常处理代码块。现在当我使用它时,它工作正常。如果出现一些错误,则抛出异常。但是如果你看到,我已在$this->abc=$this->con->prepare();语句下面写了第二个例外抛出代码块。但是,如果我在$this->abc->execute();

下面写下来,它就不起作用了

有没有办法为每个语句抛出异常? (喜欢,准备,绑定和执行)。

这是我的代码:

<?php
class Database
{
    private $servername;
    private $username;
    private $password;
    private $dbname;
    public $abc;
    public $con;
    public function __construct()
    {
       // ini_set('display_errors',1); error_reporting(E_ALL);
        $this->servername = 'localhost';
        $this->username = 'root';
        $this->password = '';
        $this->dbname = 'dbinds';
        $this->con = mysqli_connect($this->servername, $this->username, $this->password, $this->dbname);
        if($this->con->connect_error){
            die("Something: ".connect_error());
        }
        /*if(!$this->con) {
           throw new Exception("Connection can't be made");
        }*/
        return $this->con;
    }

    public function insert_data($emp_name, $emp_dept, $emp_salary)
    {
        $this->abc=$this->con->prepare("INSERT INTO table1(name, email, password) VALUES(?, ?, ?)");
        //FOLLOWING IF BLOCK
        /*if(!$this->abc) {
            throw new Exception("Couldn't insert data");
        }*/
        $this->abc->bind_param("ssi", $emp_name, $emp_dept, $emp_salary);
        $this->abc->execute();

    }
}
?>
<?php
$conobj=new Database();
$query=$conobj->insert_data("vvsdf", "vsomeone", 3445);
/*try{
    $conobj=new Database();
    $query=$conobj->insert_data("vvsdf", "vsomeone", 3445);

} catch (Exception $e ) {
    //echo "Service unavailable";
    echo "message: " . $e->getMessage();   // not in live code obviously...
   // echo $e;
    exit;
}*/
?>

1 个答案:

答案 0 :(得分:1)

您需要决定是使用procedular还是object oriented version of mysqli.

但是,您仍然可以将if条件更改为:

if (!$this->con) {
   die(mysqli_connect_error());
}

它应该有用。您还可以看到the example on manual