How to throw error when issue with mongoDB and PHP connection? - php

In php and mysql we use mysqli_error(connection); to show error but how to show error while php mongoDB connection goes wrong. $m = new MongoClient();
please help..!

Use the MongoConnectionException class..
This exception gets thrown when you have connection issues.

Related

PDO::__construct (sqlite) try/catch use

Trying to use a try/catch block for a connection to a sqlite database I found that when a database connection couldn't be made, the database file was created. Checking here the following issue is reported :
If 'example.db' does not exist, no exception is thrown but the file 'example.db' is created.
Is there a solution to this 'problem' - I hesitate to call it that because presumably this is by design.
What I need is for the error to be caught as opposed to the database created.
The solution to this would be to check if the file exists, otherwise throw an Exception :
if (!file_exists( 'example.db')) {
throw new Exception('No database file');
}

die() or try/catch when interacting with MySql database in PHP?

A lot of tutorials and books I have been over and read have used the die() method to catch an exception when interacting with a local MySQL database
For example:
mysql_connect($dbhost, $dbuser, $dbpass)or die(mysql_error());
Would a try/catch block be more beneficial over the die() method or is that just the standard way that exception handling works with db connections?
or die() is an extremely primitive way to "handle" errors and only for examples or debugging at best. In practice, it depends on how you handle your errors. You may want to return false from a function call or you may want to throw your own exception instead; e.g.:
if (!$con = mysql_connect(..)) {
throw new DatabaseConnectionError(mysql_error());
}
try..catch will do exactly nothing with mysql, since mysql never throws any exceptions. It only ever returns false on failure.
You will have to have your own error handling strategy. You'll probably want to log errors and display a user friendly error page instead of cryptic error messages. mysql is not concerned with that part. It only gives you a way to check whether an operation was successful or not (check if it returns false); what you do with this information is up to you. die kills the entire application and at least doesn't allow the problem to propagate further; but it certainly does not display any user friendly error pages.
Having said all this, mysql is old and deprecated. If you'd use something newer like PDO instead, it can properly throw exceptions itself.
The mysql_connect method does not throw exceptions and thus die() is used by many applications to terminate when there is no connection available.
You can use the solution mentioned here: how to use throw exception in mysql database connect
Included for completeness:
try
{
if ($db = mysqli_connect($hostname_db, $username_db, $password_db))
{
//do something
}
else
{
throw new Exception('Unable to connect');
}
}
catch(Exception $e)
{
echo $e->getMessage();
}
Alternatively use the new and more OOP styled database access: http://php.net/manual/en/book.pdo.php
The reason a lot of applications uses die is from the fact that they are so reliant on the database that continuing without a connection is utterly fruitless.
Edit As mentioned in the comments, the code example above is for illustrational purposes. Catching right after throwing is pointless.

Laravel postgresql error handling

I'm new to laravel and I couldn't find an answer to the problem in the documentation nor google. So here it is:
I have to use a vpn connection to connect to the postgresql database. If I'n not connected laravel gives me the following error:
SQLSTATE[08006] [7] could not connect to server: Connection timed
out.....
How do I tell laravel to ignore that error and instead just return a message "no connection"?
$export = DB::connection('pgsql')->select("SOME SQL");
I tried the "#" before the DB, but that doesn't seem to do the trick.
Add this to your routes.php (top of it) or your start.php:
App::error(function(\Exception $e)
{
return "Error handled!";
});
And try again:
$export = DB::connection('pgsql')->select("SOME SQL");
It will catch the error and now you can do whatever you need with it.
If you return null from that error handler, Laravel will catch the error and do what it is doing now.

Implementing Transactions in mysql via php

Below are my queries
$db= new mysqli('localhost','user','passcode','dbname');
try {
// First of all, let's begin a transaction
$db->beginTransaction();
// A set of queries; if one fails, an exception should be thrown
$query1="insert into table1(id,name) values('1','Dan')";
$query2="insert into table2(id,name) values('2','Anaba')";
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$db->commit();
} catch (Exception $e) {
// An exception has been thrown
// We must rollback the transaction
$db->rollback();
}
Please I am trying to implement transaction in mysql queries through php, I would like to fail all queries when one of the queries fail. The above code throws an error("Fatal error: Call to undefined method mysqli::beginTransaction()").Please is there any better solution or idea to solve the problem.Thanks for your help
$db->begin_transaction();
not
$db->beginTransaction();
http://www.php.net/manual/en/mysqli.begin-transaction.php
If earlier than PHP 5.5, then use
$db->autocommit(true);
instead
According to the documentation, begin_transaction() is new in PHP 5.5. (just released a couple weeks ago)
If you're getting an error saying that it doesn't exist, it probably means you're using an older version of PHP.
If you think you are running PHP 5.5, please verify your PHP version by running this earlier in your same script:
echo(phpversion());
Sometimes there's multiple versions of PHP present on a machine, and your script may not actually be executing in the version that you think it is.
You could implement a $count, something like that:
$err_count = 0;
$query1 = "insert into table1(id,name) values('1','Dan')";
if(!$query1)
$err_count++;
if($err_count>0)
throw new Exception("error msg");

mongoDB authentication error

I'm new at mongoDB and am trying to connect using php driver..
this is my code :
$this->connection = new Mongo("mongodb://tatao_user:tatao_pass#ds043047.mongolab.com:43047/tatao");
but it didn't work and resulting in the error below :
Fatal error: Uncaught exception 'MongoConnectionException' with message 'Couldn't authenticate with database tatao: username [tatao_user]'
I've also tried using the shell, but the reuslt is the same.
please help....
Thx B4...
First of all you need to check if mongodb is running and you have no errors.
Then if you are sure your credential (user and password) are right try this:
<?php
$mongo = new Mongo();
$db = $mongo->db_name; //replace db_name with your db name obviously
$username = "myuser";
$password = "mypassword";
$db->authenticate($username, $password);
?>
you should also check the manual:
http://php.net/manual/en/mongo.connecting.php
Then, i use Codeigniter too, and there is a really good library for mongodb, simple and fast, using Active Records and all the staffs as for the standard database library of CI.
I really suggest you to use that, you can check that here:
https://github.com/alexbilbie/codeigniter-mongodb-library

Categories