How To Catch Exception DB::unprepared() - php

I want to run SQL script file in Laravel 5.5 and I use DB::unprepared($sql) which is good so far. But I found that DB::unprepared($sql) seems didn't return any error Exception. I try with different method but still didn't work.
Here some Exception class that I tried: \Exception, PDOException, \Illuminate\Database\QueryException, but didn't work.
Try tried get bolean return from DP::unprepared($sql) by doing this $return = DB::unprepared($sql); var_dump($return); but always return TRUE
I tried using DB::statement($sql), but it looks like use only for executing statement per statement. I need to run a whole sql file without any modification.
Could anyone help me how to catch any SQL script error? Any laravel function method that could help me catch SQL exception?

#Kenjiro, I'm sure you already solved your problem, one a half year past. But, if I nailed it, please mark my answer as it will help fellows with the same problem in the future. This post was the first when googling and it has no answer...
Well, it seems that, like me, you were submiting a multistatement query to DB::unprepared.
Say:
$sql = '
drop temporary table if exists tmp_data;
create temporary table tmp_data
select1 *
from data;'
$result = DB::unprepared($sql)
Even with the typo in select1, the code will run and $result will be true.
To make it work as expected we have to submit each single statement:
$sql = 'drop temporary table if exists tmp_data;'
DB::unprepared($sql);
$sql = '
create temporary table tmp_data
select1 *
from data;'
DB::unprepared($sql)
No need to check the result. The second call to unprepared will raise an exception.
That's it.

You can check it with try catch :
try {
//your code
} catch(\Illuminate\Database\QueryException $ex){
dd($ex->getMessage());
// Note any method of class PDOException can be called on $ex.
}
Also check For Reference : Check This out

Related

PDO - Catch if any of these queries returns an empty result

I am using Medoo (a PHP DB framework using PDO) with PDO::ERRMODE_EXCEPTION enabled. I have some queries in a try and catch block and I want to throw an exception if any of those queries return an empty result.
PS: $database->get() is a simple PDO SELECT returning a single row. I don't think it's relevant and I think my example applies also to PDO without frameworks.
try {
$q1 = $database->get(..);
$q2 = $database->get(..);
$q3 = $database->get(..);
$q4 = $database->get(..);
} catch (PDOException $e) {
die ("There was an error in a query.");
}
Right now I get into the catch block only if there is an error in the query, like I try to select a table that doesn't exist. I want to find the optimal way to avoid checking if every single query doesn't return an empty result manually, like I don't want to do this:
if (!$q1) { echo "No result"; }
if (!$q2) { echo "No result"; }
...
Is there a more generic approach?
Your logic is wrong, an Exception is an event that occurs during program execution that disrupts normal flow.
Query that returns an empty result set is not disrupting normal flow of your program, because that query executed successfully.
If you think that it's a good idea to use exceptions in order to signal that an empty result is returned, you have to throw that exception.
Eloquent, which is an ORM used by Laravel contains a method called firstOrFail and findOrFail which perform what you're after.
Your option is to either create such a method for Medoo or use a proper ORM such as Doctrine or Eloquent that can help you achieve such behavior out of the box.

Handling errors in PDO when MySQL query fails

I've recently changed all my mysql.* to PDO. I've been having a few issues and trying to get used to it.
My question is how to properly call an error when there is an issue in the sql statement. Normally I wouldn't use try, catch but is there another alternative?
Suppose I have the following:
private function init()
{
$query = $this->_PDO->prepare("SELECT * FROM here WHR name='john'");
if($query->execute())
{
$this->_sql_rows = $query->rowCount();
}
else
{
print_r($query->errorInfo());
}
}
This checks whether the execute method worked and if not, output errors. In this case it should as there is a spelling mistake. Normally when I do this, I never see any errors come out and must always use the method above to output an error. Is this a reliable and appropriate way of handling such errors?
Nope, it is not.
Just like almost every PHP user, you have quite vague and uncertain idea on error handling. And the code mostly looks like a dummy code from sandbox example. Speaking of your current approach, frankly - it's just terrible. On a live site it will only scare an innocent user, while webmaster would have no idea what's going on.
So, first of all you have to make your mind what is error handling you are looking for.
There are different possible scenarios, but most convenient is just to follow the way PHP handles all other errors. To do that just set PDO in exception mode. This way you'll be always notified of all the errors occurred. So - just add this line right after connect.
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
and thus your function become short and clean
private function checkUser($user)
{
$stmt = $this->_PDO->prepare("SELECT 1 FROM users WHERE name=?");
$stmt->execute(array($user));
return $stmt->fetchColumn();
}

ActiveCollab Custom Insert/Update query issue

I tried to execute some custom queries using DB::execute() function by passing query as a parameter to this function - update query on existing table. Before running this query I checked the connection object like this $connection = DB::getConnection(); and it returned a connection identifier. Then while executing query it returned bool true from execute function, though changes were not there in database table fields. Also if I pass query with wrong syntax, it is giving error.
Is there any rollback process going on in background with update query statement in ActiveCollab? If yes how to stop this rollback to avoid the changes done by my update query ?
Could anyone tell me what could be the issue here ?
All uncommitted transactions are automatically rolled back on script shutdown so you need to make sure that you are committing transactions that you opened:
try {
DB::beginWork();
// Do something
DB::commit();
} catch(Exception $e) {
DB::rollback();
throw $e;
}
or:
DB::transact(function() {
// Do something
});
If you are within a nested transaction and outer transactions gets rolled back, your updates will be rolled back as well.

How to catch DB errors in CodeIgniter PHP

I am new to CodeIgniter, PHP and MySQL. I want to handle the DB generated errors. From one of the post in Stackoverflow, I knew that by following statement one can catch the error.
$this->db->_error_message();
But I cannot figure out the exact syntax of using that. Suppose I want to update the records of table named "table_name" by the following statement:
$array['rank']="8";
$array['class']="XII";
$this->db->where('roll_no',$roll_no);
$this->db->update("table_name", $array);
Here in the above code I want to catch the DB error whenever any DB level violation occurs i.e. either field name is not valid or some unique constraint violation occurs. If anyone helps me to fix that I would be really grateful. Thank you.
You can debug the database error on database configuration in (config/database.php) like this:
$db['default']['db_debug'] = TRUE;
More info read here
Also you can use Profiler to see all the queries and their speed. In controller you can put this:
$this->output->enable_profiler(TRUE);
More information read here
codeIgniter has functions for it
$this->db->_error_message();
$this->db->_error_number();
if(!$this->db->update("table_name", $array))
{
$this->db->_error_message();
$this->db->_error_number();
}
On Codeigniter version 2,
$this->db->_error_message();
$this->db->_error_number();
On Codeigniter version 3,
$db_error = $this->db->error();
echo '<pre>';print_r($db_error);echo '</pre>';

how to handle exceptions/errors in php?

when using 3rd part libraries they tend to throw exceptions to the browser and hence kill the script.
eg. if im using doctrine and insert a duplicate record to the database it will throw an exception.
i wonder, what is best practice for handling these exceptions.
should i always do a try...catch?
but doesn't that mean that i will have try...catch all over the script and for every single function/class i use? Or is it just for debugging?
i don't quite get the picture.
Cause if a record already exists in a database, i want to tell the user "Record already exists".
And if i code a library or a function, should i always use "throw new Expcetion($message, $code)" when i want to create an error?
Please shed a light on how one should create/handle exceptions/errors.
Thanks
The only way to catch these exceptions is to use a try catch block. Or if you don't want the exception to occur in the first place you need to do your due diligence and check if the record already exists before you try to insert the record.
If it feels like you're using this all over the place then maybe you need to create a method that takes care of this for you (Dont Repeat Yourself).
I don't know Doctrine, but regarding your concrete usage, maybe there is a way to determine if you are facing a duplicate entry, something like :
try {
/* Doctrine code here */
} catch (DuplicateEntryException $e) {
/* The record already exists */
} catch (Exception $e) {
/* Unexpected error handling */
}
Or maybe you have to check if the Exception code equals 1062, which is the MySQL error code for duplicate entries.
Any code that may throw an exception should be in a try/catch block. It is difficult in PHP because you cannot know which method throws an Exception.
You should also have a big try/catch block in your main PHP file that avoids displaying the stack trace to the user, and that logs the cause. Maybe you can use set_exception_handler for this.

Categories