Is it something incomplete/ incorrect in the error class function below? I can never get any error message from it when a query is incorrect,
#connects the database and handling the result
class __database {
protected $connection = null;
protected $error = null;
#make a connection
public function __construct($hostname,$username,$password,$database)
{
$this -> connection = new mysqli($hostname,$username,$password,$database);
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
#fetches all result rows as an associative array, a numeric array, or both
public function fetch_all($query)
{
$result = $this -> connection -> query($query);
if($result)
{
return $result -> fetch_all(MYSQLI_ASSOC);
}
else
{
$this -> error = $this -> connection -> error;
return $this -> error;
}
}
#display error
public function get_error()
{
return $this -> error;
}
#closes the database connection when object is destroyed.
public function __destruct()
{
$this -> connection -> close();
}
}
public function get_error() seems to be useless in my db class… I have read about php Exception but I don’t know how to incorporate it into the this db class above! please advise…
EDIT:
I tried to change the code into this,
# return the current row of a result set as an object
public function fetch_object($query)
{
$result = $this->connection->query($query);
if($result)
{
...
}
else
{
__database::get_error();
}
}
and the error class function,
#display error
public function get_error()
{
$this->error = $this->connection->error;
return $this->error;
}
So I thought it should trigger the get_error() function, but still nothing has been displayed from the error function…
Firstly, if you want to take full advantage of the mysqli class then you should extend it, and just overriding where needed.
This will allow mysqli to handle the errors and allow you to easily access them, there is not point in creating a class that would just mimic a class, your better extending the class itself.
Secondly its bad practice to space out your code, it should not effect the way php interpretes the code but it can confuse further developers and cause issues in the long run when it comes down to shared development.
Simple example: