Reputation: 13
Sometimes I get a fatal error in this line
$result = $db->execute($query);
$primary = $result->getRows();
Fatal error: Call to a member function getRows() on a non-object
I'm searching for a solution to catch this error and redirect to index page.
Rewriting something is complicated, because the system is old.
Upvotes: 0
Views: 6480
Reputation: 24645
Normally you can't catch an error... only exceptions.... luckily with PHP you can set up an error_handler that does throw exceptions. (from comments on php ErrorException page)
class ErrorHandler extends Exception {
protected $severity;
public function __construct($message, $code, $severity, $filename, $lineno) {
$this->message = $message;
$this->code = $code;
$this->severity = $severity;
$this->file = $filename;
$this->line = $lineno;
}
public function getSeverity() {
return $this->severity;
}
}
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorHandler($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler", E_ALL);
So for your specific problem you would just do:
try{
$result = $db->execute($query);
$primary = $result->getRows();
} catch (ErrorHandler $e){
header("Location: /index.php");
exit;
}
Upvotes: 0
Reputation: 593
If you get the error message "header already sent" it's because something is already outputted. For instance:
echo "hello world;";
header("Location: errorpage.php");
or:
<?php // notice the space before <?php
header("Location: errorpage.php");
?>
Upvotes: -1
Reputation: 101
We need to know what $db is, you have not included the code where $db is initialised or informed us as to what this references.
Assuming you are using the PDO library, the PDO object itself has PDO::exec() and the PDOStatement object has PDOStatement::execute(). I therefore assume $db is an instance of PDOStatement and you are calling the execute() method, which returns a boolean, false upon a failure and true upon success - it does not return an object upon success. If successful, you should then call $db->fetchAll();
if (!$db->execute($query)) {
header("Location: error.php");
exit;
}
$rows = $db->fetchAll();
Upvotes: 0
Reputation: 157839
In the first place, there shouldn't be an error either way.
You have to fix your code to correct the error, instead of writing new code to handle it.
Get the error message out of DB to see the certain problem that caused this error and fix it.
Also
Upvotes: 1
Reputation: 967
The problem here is that execute() will return FALSE under some circumstances and a boolean is not the result object.
To avoid this error you should always be checking the output of execute() if it was even executed successfully.
For example:
$result = $db->execute($query);
if ($result !=== false) {
$primary = $result->getRows();
}
Upvotes: 0
Reputation: 10975
Something like this:
$result = $db->execute($query);
if ($result===false) {
header("Location: errorpage.php");
exit;
}
$primary = $result->getRows();
Upvotes: 2