I'm using this code inside the public function __construct() of a class:
$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or throw new Exception("Couldn't connect to database.");
BASE_DB_HOST, BASE_DB_USER and BASE_DB_PASS are defined. I get the following error:
Parse error: syntax error, unexpected T_THROW in /home/... on line 6
Am I not allowed to use the or construction with Exceptions? How can I workaround this?
Try using like this and let me know if its work for you or not-
<?php
function throwException() {
throw new Exception("Couldn't connect to database.");
}
$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) OR throwException();
?>
Reference - http://www.php.net/manual/en/language.exceptions.php#81960
Another way is to throw an exception in an anonymous function after the or logical operator.
$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or call_user_func(function() { throw new Exception("Couldn't connect to database."); });
Related
I am using the ImapMail Library and try to initiate a new Mailbox:
try{
$mailbox = new ImapMailbox($url, $username, $password);
}catch (\Exception $e){
return new Response("fail");
}
But the above try/catch does not work, although symfony gives me this:
Connection error: (is empty)
500 Internal Server Error - Exception
the Stacktrace
in vendor/php-imap/php-imap/src/PhpImap/Mailbox.php at line 67:
protected function initImapStream() {
$imapStream = #imap_open($this->imapPath, $this->imapLogin, $this->imapPassword, $this->imapOptions, $this->imapRetriesNum, $this->imapParams);
if(!$imapStream) {
throw new Exception('Connection error: ' . imap_last_error());
}
return $imapStream;
}
(Direct link to function on github)
It does throw a new Exception, why can't I catch it?
Any hint appreciated!
The reason is very simple. You call only class constructor in try block. If you look into the class source code, you will see that constructor does call nothing.
https://github.com/barbushin/php-imap/blob/master/src/PhpImap/Mailbox.php#L20-L31
It means code throwing exception must be under you try/catch. You have to move it inside try block if you want to catch the exception. I am talking about $mailbox->checkMailbox(). This command throws exception.
I'm new to php and I'm writing a test function to test a class I have already written. However, I'm not sure how I should properly make a call to the function assertTrue().
Here is the code I have:
<?php
require_once(dirname(__FILE__) . '/simpletest/autorun.php');
require_once('../db/fileToBeTested.php');
class TestDbManager extends UnitTestCase {
function TestDbManager(){
$this->UnitTestCase("Test DB Manager");
}
// Function to test if isTableExisting() method works correctly
function testIsTableExisting() {
$testDB = new DB("localhost", "root", "password", "GraphAppDB", "3306", "empty#empty.com", true, "GraphApp")
$this->assertTrue($testDB->isTableExisting("users"), "users table exists");
$this->assertFalse($testDB->isTableExisting("notAValidTable"), "notAValidTable does not exist");
$this->assertFalse($testDB->isTableExisting(""));
}
}
?>
And here is the error I am getting:
Parse error: syntax error, unexpected '$this' (T_VARIABLE) in
/Applications/XAMPP/xamppfiles/htdocs/GraphApp/tests/TestDbManager.php
on line 14
You're missing a ; after
$testDB = new DB("localhost", "root", "password", "GraphAppDB", "3306", "empty#empty.com", true, "GraphApp")
The call to assertTrue is probably fine.
I'm using the following script to use a database using PHP:
try{
$db = new PDO('mysql:host='.$host.';port='.$port.';dbname='.$db, $user, $pass, $options);
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
Now, I want to use this database handle to do a request using this code:
try{
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
Here is the problem:
When the connection to the DB is OK, everything works,
When the connection fails but I don't use the DB, I have the $GLOBALS['errors'][] array and the script is still running afterwards,
When the connection to the DB has failed, I get the following fatal error:
Notice: Undefined variable: db in C:\xampp\htdocs[...]\test.php on line 32
Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs[...]\test.php on line 32
Note: Line 32 is the $query = $db->prepare(...) instruction.
That is to say, the script crashes, and the try/catch seems to be useless. Do you know why this second try/catch don't works and how to solve it?
Thanks for the help!
EDIT: There are some really good replies. I've validated one which is not exactly what I wanted to do, but which is probably the best approach.
try/catch blocks only work for thrown exceptions (throw Exception or a subclass of Exception must be called). You cannot catch fatal errors using try/catch.
If your DB connection cannot be established, I would consider it fatal since you probably need your DB to do anything meaningful on the page.
PDO will throw an exception if the connection cannot be established. Your specific problem is that $db is not defined when you try to call a method with it so you get a null pointer (sort of) which is fatal. Rather than jump through if ($db == null) hoops as others are suggesting, you should just fix your code to make sure that $db is either always defined when you need it or have a less fragile way of making sure a DB connection is available in the code that uses it.
If you really want to "catch" fatal errors, use set_error_handler, but this still stops script execution on fatal errors.
In PHP7, we now can using try catch fatal error with simple work
try {
do some thing evil
} catch (Error $e) {
echo 'Now you can catch me!';
}
But usualy, we should avoid using catch Error, because it involve to miss code which is belong to programmer's reponsibility :-)
I will not report what has already been written about testing if $db is empty. Just add that a "clean" solution is to artificially create an exception if the connection to the database failed:
if ($db == NULL) throw new Exception('Connection failed.');
Insert the previous line in the try - catch as follow:
try{
// This line create an exception if $db is empty
if ($db == NULL) throw new Exception('Connection failed.');
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
Hope this will help others!
If database connection fails, $db from your first try .. catch block will be null. That's why later you cannot use a member of non-object, in your case $db->prepare(...). Before using this add
if ($db) {
// other try catch statement
}
This will ensure that you have db instance to work with it.
Try adding the following if statement :
if ($db) {
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(....);
}
else die('Connection lost');
try{
if(!is_null($db))
{
$query = $db->prepare("INSERT INTO users (...) VALUES (...);");
$query->execute(array(
'...' => $...,
'...' => $...
));
}
}
catch(Exception $e){
$GLOBALS['errors'][] = $e;
}
How do I know if there's an error if I did $db = new SQLite3("somedb.db"); in PHP? Right now the $db doesn't really give me any sort of error?
I can check for file existance, but I'm unsure if there could be any other errors when I open a connection.
You should enable exceptions and instantiate in a try-catch block.
It is not obvious from the documentation but if you use the constructor to open the database it will throw an exception on error.
Further if you set the flag SQLITE3_OPEN_READWRITE in the second argument then it will also throw an exception when the database does not exist (rather than creating it).
class Database extends SQLite3
{
function __construct($dbName)
{
$this->enableExceptions(true);
try
{
parent::__construct($dbName, SQLITE3_OPEN_READWRITE );
}
catch(Exception $ex) { die( $ex->getMessage() ); }
}
Try:
echo $db->lastErrorMsg();
I have the following PHP code:
foreach (...) {
try {
$Object = MyDataMapper::getById(123);
if (!$Object->propertyIsTrue()) {
continue;
}
}
catch (Exception $e) {
continue;
}
}
MyDataMapper::getById() will throw an Exception if a database record is not found. Here is the definition of that method:
public static function getById($id) {
$query = "SELECT * FROM table WHERE id = $id";
$Connection = Database::getInstance();
$Statement = $Connection->prepare($query);
$Statement->execute();
if ($Statement->rowCount() == 0) {
throw new Exception("Record does not exist!");
return null;
}
$row = $Statement->fetch();
return self::create($row);
}
When this code is called for a database record id that does not exist, I get a fatal uncaught exception 'Exception' error.
Why is this? Clearly I am catching the exception... What am I doing wrong?
I am sure an exception is being thrown. Is there something wrong with how I am handling the exception--maybe with the continue?
EDIT
Thanks to help from jitter, the following workaround solves this problem:
if (!$Object->propertyIsTrue()) {
// Workaround to eAccelerator bug 291 (http://eaccelerator.net/ticket/291).
$foo = 555;
continue;
}
What PHP version? -> 5.2.9
Are you using eAccelerator (which version)? -> 0.9.5.3 with ionCube PHP Loader v3.1.34
What kind of exception do you throw? -> normal Exception
There are known problems in certain PHP + eAccelerator versions in regard to try-catch blocks being optimized away.
Check the eAccelerator bug-tracker:
For a starter check the tickets
291 Incorrect handling of exception
314 Exceptions not catched
317 Exception not caught
and try disabling eAccelerator.
I think it may be because you're calling a static method, but I could be wrong. Is it possible for you to test this by instantiating MyDataMapper and calling the method from the object itself?