I am looking for a way to build a handler or edit a php object, the following is an example for mysqli
I have a system with many files using the mysqli object in a variable
$my_var=new mysqli($host, $user, $pass, $base);
Files call this to do queries and get the results like this:
$q=$my_var->query("SELECT * FROM table");
$q->fetch_assoc();
if there is an error on the query, $my_var->error
will be populated on the first line and will throw an error 500 on the second line.
I am looking for a way to build a handler for $my_var->error
and throw the error before any fetch_* method is called, so,
is there any way to build a handler/listener for $my_var->error
?
if this is not possible, is there any way to override mysqli fetch_assoc()
, fetch_row() and fetch_array() methods to check if $my_var->error
is true and show the error before continue?
I know about try{}catch()
, throw new Exception
and or die()
methods, but these mean to edit every fetch_* in the system, I would like to do it editing the connection file only.
Thank you!
---editing---
I think prepared statements are not what I am looking for.
---editing 2---
And no, I am not looking how to get mysqli errors.
Thank you for your help fyrye!
---Answer Final Code---
class mysqli2{
private $c;
function __construct(...$args){ // open connection
$this->c=new mysqli(...$args);
if(!empty($this->c->error)){ // check for errors
echo("<script>console.error(\"MySQL: ".$this->c->error."\");</script>");
}
}
function query($query, $resultmode = MYSQLI_STORE_RESULT){
$r=$this->c->query($query, $resultmode); // make query
if(!empty($this->c->error)){ // check for errors
echo("<script>console.error(\"MySQL: ".$this->c->error."\");</script>");
}
return $r; // returns query results
}
function __call($method, $args){ // calls others mysqli methods
return $this->c->$method(...$args);
}
function __get($name){ // get all the properties
return $this->c->$name;
}
function __set($name, $value){ // set all the properties
if (property_exists($this->c, $name))$this->c->$name = $value;
}
}