Codeigniter - throw exception if database transaction fails - php

I am trying catch database errors within a transaction and if one occurs then rollback and throw an exception.
However, the code is stopping and displaying the db error screen before it throws the exception.
Any ideas how I can make it detect db error without stopping running the subsequent code?
try {
$this->my_function($data);
} catch (Exception $e) {
var_dump($e);
}
private function my_function($data)
{
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$this->db->trans_rollback();
throw new Exception('Exception message here...');
}
}
$this->db->trans_complete();
}

This has been answered before on this question
As answered by cwallenpoole:
In application/config/database.php set
// suppress error output to the screen
$db['default']['db_debug'] = FALSE;
In your model or controller:
// try the select.
$dbRet = $this->db->select($table, $dataArray);
// select has had some problem.
if( !$dbRet )
{
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
// Do something with the error message or just show_404();
}
Or in you case:
private function my_function($data)
{
$errors = array();
$this->db->trans_start();
foreach($data as $reg)
{
$sql = $this->db->insert_string('my_table', $reg);
if($this->db->query($sql))
{
continue;
} else {
$errNo = $this->db->_error_number()
$errMess = $this->db->_error_message();
array_push($errors, array($errNo, $errMess));
}
}
$this->db->trans_complete();
// use $errors...
}
Even better
I believe this question has all the answers you need because it takes multiple inserts into account and let's you finish the once that did not return an error.

Related

Rolling back MySQL queries

If I have multiple queries on chain, on a structure based on IFs, like this:
$query1 = mysqli_query("query here");
if(!query1){
//display error
} else {
$query2 = mysqli_query("another query here");
if(!query2){
//display error
//rollback the query1
} else {
query3 = mysqli_query("yet again another query");
if(!query3) {
//display error
//rollback the query2
//rollback the query1
} else {
query4 = mysqli_query("eh.. another one");
if(!query4){
//display error
//rollback the query3
//rollback the query2
//rollback the query1
} else {
return success;
}
}
}
}
Is there a best way to rollback the previous query, if the next one fails?
Otherwise I'm gonna have the first 2 query successfull, which edited the database, but the 3° failed, so 3° and 4° didn't edit the dabatase, with the result of having it corrupted.
I thought about something like:
...
$query2 = mysqli_query("another query here");
if(!query2){
//display error
$rollback = mysqli_query("query to rollback query1");
} else {
query3 = mysqli_query("yet again another query");
if(!query3) {
//display error
$rollback = mysqli_query("query to rollback query2");
$rollback = mysqli_query("query to rollback query1");
} else {
...
But the above method grants even more chances to fail more queries.
Is there any other more effective methods?
This is how i would do it with mysqli:
Configure mysqli (somewehere at the begining of your application) to throw exceptions when a query fails.
mysqli_report(MYSQLI_REPORT_STRICT);
This way you will not need all the if .. elseif .. else.
$connection->begin_transaction();
try {
$result1 = $connection->query("query 1");
// do something with $result1
$result2 = $connection->query("query 2");
// do something with $result2
$result3 = $connection->query("query 3");
// do something with $result3
// you will not get here if any of the queries fails
$connection->commit();
} catch (Exception $e) {
// if any of the queries fails, the following code will be executed
$connection->rollback(); // roll back everything to the point of begin_transaction()
// do other stuff to handle the error
}
Update
Usually the user don't care about, why his action failed. If a query fails, it's never the users fault. It's either the fault of the developer or of the environment. So there shouldn't be a reason to render an error message depending on which query failed.
Note that if the users intput is the source of the failed query, then
you didn't validate the input properly
your queries are not injection safe (If the input can cause an SQL error it can also be used to compromise your DB.)
However - I don't say there can't be reasons - I just don't know any. So if you want your error message depend on which query failed, you can do the following:
$error = null;
$connection->begin_transaction();
try {
try {
$result1 = $connection->query("query 1");
} catch (Exception $e) {
$error = 'query 1 failed';
throw $e;
}
// do something with $result1
try {
$result2 = $connection->query("query 2");
} catch (Exception $e) {
$error = 'query 2 failed';
throw $e;
}
// do something with $result2
// execute more queries the same way
$connection->commit();
} catch (Exception $e) {
$connection->rollback();
// use $error to find out which query failed
// do other stuff to handle the error
}

Get the mysql data

I am trying to get a mysql data from the table, here -
try
{
$stmt = $user->prepare("SELECT status FROM users");
$result=$stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Here user is a class where prepare is db connection mysql prepare function. The error always prints - "Array!". I am new to php. Any help will be appreciated.
EDIT: I have managed to solve the problem.
You forgot the call of PDOStatement::execute(). See php.net for some examples.
Have you already tried this?
try
{
$stmt = $user->prepare("SELECT status FROM users");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if($result['status'] != "Y")
{
$error[] = "Some error warning!";
}
else
{
// Some php codes
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Regarding the Array! output: Did you post the whole code of your script? Were do you try to print the array $error?

Try Catch method in destroy function laravel

Im trying display a message when you have nothing to delete in the database instead of showing a error that says you have a null value
public function destroy($customer_id)
{
$customer_response = [];
$errormsg = "";
$customer = Customer::find($customer_id);
$result = $customer->delete();
try{
//retrieve page
if ($result){
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
}else{
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);
}catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
}
return Response::json(['errormsg'=>$errormsg]);
}
the try/catch method is not working compared to my previous store function that is working
Read up further on findOrFail. You can catch the exception it throws when it fails to find.
try {
$customer = Customer::findOrFail($customer_id);
} catch(\Exception $exception){
dd($exception);
$errormsg = 'No Customer to de!' . $exception->getCode();
return Response::json(['errormsg'=>$errormsg]);
}
$result = $customer->delete();
if ($result) {
$customer_response['result'] = true;
$customer_response['message'] = "Customer Successfully Deleted!";
} else {
$customer_response['result'] = false;
$customer_response['message'] = "Customer was not Deleted, Try Again!";
}
return json_encode($customer_response, JSON_PRETTY_PRINT);

error class not catching thrown errors

I have an exception class that looks like this
<?php
class Errors{
public function displayError(Exception $e){
$trace = $e->getTrace();
if($trace[0]['class'] != ""){
$class = $trace[0]['class'];
$method = $trace[0]['function'];
$file = $trace[0]['file'];
$line = $trace[0]['line'];
$error_message = $e->getMessage().
"<br /> Class/Method : ".$class." <==> ".$method.
"<br /> File : ".$file.
"<br /> Line : ".$line;
}
return $error_message;
}
}
?>
This works fine for many errors that are thrown due do typos/column count not matching value count, but when I throw an exception from the code myself, I get an error. For example
try{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
$stmt->execute();
if ($stmt->rowCount() < 1){
throw new Exception('The Link expired, request a new one');
} else {
throw new Exception('The Link is invalid, please request a new one');
}
}
catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
I get Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one' error when I run the code. If I remove that line, and induce an error by spelling SELECT as SLECT, the error class works fine.
How can I make in such a way that the error class will catch all types of errors ?
The problem is NOT all exceptions are PDOExceptions.You code cacthes only PDOException which means new Exception won't be catched. Try :
try
{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
...
}
catch (PDOException $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
catch (Exception $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
The reason why your code works when you spell SELECT as SLECT is because you triggered a PDOException instead of a new Exception.

MySQL 5.5 SIGNAL and PDO exceptions

I have a TRIGGER for a MySQL table which raises exception with SIGNAL when there's something wrong with the data provided. How can I catch this exception in PHP with PDO?
Thanks in advance.
UPDATE
More information on my problem: I am executing several queries within a transaction and I want to rollback the transaction if one of them fails because there was a SIGNAL. Currently a signal is activated but all the other queries are executed.
ANOTHER UPDATE
So far I've got:
try {
$db->beginTransaction();
if (!$db->query('UPDATE accounts SET amount = amount - 10 WHERE id = 1')) {
throw new Exception($db->errorInfo()[2]);
}
if (!$db->query('UPDATE accounts SET amount = amount + 10 WHERE id = 2')) {
throw new Exception($db->errorInfo()[2]);
}
$db->commit();
} catch (Exception $e) {
$db->rollback();
echo 'There was an error: ' . $e->getMessage();
}
Is this the proper way to do a transaction with handling the exceptions?
Sorry if my question is too broad.
Try something like:
$ls_error = "";
$mysqli->autocommit(FALSE);
// first sql
if (!$mysqli->query($sql)) {
$ls_error .= sprintf("Error: %d: %s\n",$mysqli->errno, $mysqli->error);
$mysqli->rollback();
}
// second one
if ($ls_error == "") {
if (!$mysqli->query($sql)) {
$ls_error .= sprintf("Error: %d: %s\n",$mysqli->errno, $mysqli->error);
$mysqli->rollback();
}
}
// third one
if ($ls_error == "") {
if (!$mysqli->query($sql)) {
$ls_error .= sprintf("Error: %d: %s\n",$mysqli->errno, $mysqli->error);
$mysqli->rollback();
}
}
if ($ls_error == "") {
$mysqli->commit();
} else {
echo $ls_error;
}
Abstract example. I have the solution works without any problems.
Trigger:
IF NEW.value < 0 THEN
SET #msg = CONCAT('Wrong count_from value! ', NEW.value);
SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = #msg;
END IF;
php (PDO):
try {
$conn->query('INSERT INTO `table` SET `value` = -1');
} catch (Exception $err) {
$error_message = $conn->query('SELECT #msg')->fetchColumn();
}

Categories