2016-10-24 07:26
浏览 99

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

Main question:

I'm trying to print error on web page if the connection to MySQL server is not made. For this, I written a wrong database name $this->dbname = 'dbinds'; (actual is dbind). But the die statement is not executing. When I open the page, it simply doesn't load. It shows error: The localhost page isn’t working. Am I doing something wrong?

Another question: I've commented the exception handling code block. Now when I use it, it works fine. The exception is thrown if there's some mistake. But if you see, I've written the 2nd exception throw code block below $this->abc=$this->con->prepare(); statement. But it doesn't work if I write this below $this->abc->execute();

Is there any way to throw exceptions for each statement? (Like, prepare, bind and execute).

Here's my code:

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);
            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(?, ?, ?)");
        /*if(!$this->abc) {
            throw new Exception("Couldn't insert data");
        $this->abc->bind_param("ssi", $emp_name, $emp_dept, $emp_salary);

$conobj=new Database();
$query=$conobj->insert_data("vvsdf", "vsomeone", 3445);
    $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;
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douxian1770
    douxian1770 2016-10-24 07:29

    You need to decide whether you use procedular or object oriented version of mysqli.

    However, still you can change your if condtion to:

    if (!$this->con) {

    it should work. You can also see the example on manual

    点赞 评论