This will always evaluate to TRUE because $this->link is a MySQLi object you have just created. What you need to do is check its connection_error property:
(As a side note: always use curly brackets with if constructs. It’s just good practice.)
public function connect()
{
$this->link = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if ($this->link->connect_error) {
throw New Exception(mysqli_error());
}
return $this->link;
}
I tried what you said and it’s working but its also displaying an error:
Warning: mysqli_error() expects exactly 1 parameter, 0 given in C:\Users\9three\Desktop\Server\htdocs\library\mysqli.package.php on line 23
I’m assuming it’s because im not suppressing the error messages from within the class (eg. @) ?
BTW, is there an exception list I can view online? The only one I know is catch (Exception $e). I’m assuming (I’m a java developer) that you have more than one exception available through PHP?
P.S. I don’t use curly bracers because it’s only one line. I use curly bracers for more than one line.
Never use error suppression. You should handle errors, not suppress them.
You should use $this->link->connect_error instead of mysqli_error().
Exception is the only native exception class. You can, however, extend it and build your own.
Yes, I know. It’s bad practice. First of all the code is more readable with braces even if there’s only one line. Also, you won’t have to worry that you forget to add braces if you want to add another line in the future. Always use braces.
You shouldn’t use procedural access to MySQLi (it’s deprecated). Use OO manner instead: MySQLi->connect_error (so in your code that would be $this->link->connect_error).
BTW, is there an exception list I can view online? The only one I know is catch (Exception $e). I’m assuming (I’m a java developer) that you have more than one exception available through PHP?
eg. in java you have all kinds of different exceptions:
As far as I’m aware, most native PHP objects throw a generic Exception. Although there is nothing stopping you catching the original exception and throw an extending exception which is a bit more descriptive.
Exceptions in PHP are relatively new, and therefore appear quite lacking compared to other more mature OOP languages.
I’m having an issue. It’s always returning “connected” whether the data base name is correct or not.
public function connect()
{
$this->link = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if ($this->link->connect_error) { // Error returned true
Throw New Exception($this->link->connect_error);
}
return $this->link; //No exception was thrown, return $this->link
}