Try Catch method in destroy function laravel - php

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);

Related

PHP verify in db if exist duplicate

I have this function:
public function addToFavoriteList($eventId, $userId)
{
$sql = "INSERT INTO favorites (eventi_id, user_id) VALUES ($eventId, $userId)";
$resultSet = $this->db->execute($sql);
if (!$resultSet) {
return array('error' => 'event exsist in favorites');
}
return array('error' => '');
}
and i want to check if the event alredy exist in db so i can show and error message for the user.
I write something like that but it doesen't work.
if (isset($_POST['addToFavourite'])) {
$eventId = htmlspecialchars(trim($_POST['id']));
$addToFavoriteOutcome = $eventMgr->addToFavoriteList($eventId, $userId);
if (isset($addToFavoriteOutcome)) {
$errorMessage = $addToFavoriteOutcome['error'];
}
}
Try changing this:
if (isset($addToFavoriteOutcome)) {
$errorMessage = $addToFavoriteOutcome['error'];
}
to this
if ($addToFavoriteOutcome) {
$errorMessage = $addToFavoriteOutcome['error'];
}

Query executed without errors but no data in database

After executing the SQL file below to create the appropriate tables(which gets executed correctly without errors),
<?php
try {
require_once 'dbcon.php';
$sql_file = 'mysql.sql';
$contents = file_get_contents($sql_file);
$comment_patterns = array('/\/\*.*(\n)*.*(\*\/)?/',
'/\s*--.*\n/',
'/\s*#.*\n/',
);
$contents = preg_replace($comment_patterns, "\n", $contents);
$statements = explode(";\n", $contents);
$statements = preg_replace("/\s/", ' ', $statements);
foreach ($statements as $query) {
if(trim($query) != '') {
$db->query($query);
if ($db->errno) {
throw new Exception("Fail to load data in database (".$db->errno.")");
}
}
}
Running the following query right after the foreach gets executed successfully without errors and success message gets printed. However , no data gets inserted into the database.
$cql = "INSERT INTO config (logo,brand,provider,mail_type,url) VALUES(?,?,?,?,?)";
$cstmt = $db->prepare($cql);
$sch_logo = 'logo.png';
$sch_brand = 'brand.png';
$provider = 'other';
$mail_type = 'mail';
$cstmt->bind_param('sssss',$sch_logo,$sch_brand,$provider,$mail_type,$site_url);
$cstmt->execute();
if($cstmt->affected_rows === 1){
echo 'Identity verified. Thank you';
}
else{
throw new Exception("An error occurred Performing this operation.");
}
}
catch(Exception $e) {
error_log($e->getMessage());
echo ' <div class="text-warning">
<b>'.$e->getMessage().'</b> </div>';
exit();
}
?>
I have printed out $cstmt->error and $cstmt->errno and they all return 0 . which seems fine but don't why the data doesn't get inserted into the fields. Anything am missing or doing wrong?
Try this:
$cql = "INSERT INTO config (logo,brand,provider,mail_type,url) VALUES(?,?,?,?,?)";
$cstmt = $db->prepare($cql);
$sch_logo = 'logo.png';
$sch_brand = 'brand.png';
$provider = 'other';
$mail_type = 'mail';
$cstmt->bind_param('sssss',$sch_logo,$sch_brand,$provider,$mail_type,$site_url);
**if($cstmt->execute()){**
echo 'Identity verified. Thank you';
}
else{
throw new Exception("An error occurred Performing this operation.");
}
}
catch(Exception $e) {
error_log($e->getMessage());
echo ' <div class="text-warning">
<b>'.$e->getMessage().'</b> </div>';
exit();
}

Codeigniter - throw exception if database transaction fails

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.

Simple slim session manager not read session in a different function

I am using the following slim session manager(https://github.com/bryanjhv/slim-session). I have separate functions for login, logout and user_data.
$app->post("/login", function() use ($app)
{
$input = $app->request()->getBody();
$input = json_decode($input);
try
{
if ($input->username && $input->password)
{
$user = Model::factory('Users')->where("username",$input->username)->where("password",md5($input->password))->find_one();
$session = new \SlimSession\Helper;
//set session
$session->set('userid', $user->id);
$status = 'success';
$message = 'Logged in successfully.';
}
else
{
$status = 'danger';
$message = 'Could not log you in. Please try again.';
}
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message,
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->post("/logout",function() use ($app)
{
try {
$session = new \SlimSession\Helper;
$session::destroy();
$status = 'success';
$message = 'You have been logged out successfully';
}
catch (Exception $e)
{
$status = 'danger';
$message = $e->getMessage();
}
$response = array(
'status' => $status,
'message' => $message
);
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
$app->get("/user_data", function() use ($app)
{
try
{
$session = new \SlimSession\Helper;
//get session
$userid = $session->get('userid');
$_SESSION['userid'] = $userid;
if ($_SESSION['userid'])
{
$users = Model::factory('Users')->where('id',$_SESSION['userid'])->find_one();
$response = array(
'id'=>$users->id,
'username'=>$users->username,
'email'=>$users->email,
'phone_number'=>$users->phone_number,
'password'=>$users->password,
'type'=>$users->type,
'credits'=>$users->credits,
'profile_picture'=>$users->profile_picture,
);
}
else
{
$status = "danger";
$message = 'You need to be logged in to do that.';
$response = array(
'status' => $status,
'message' => $message
);
}
}
catch (Exception $e)
{
$status = "danger";
$message = $e->getMessage();
$response = array(
'status' => $status,
'message' => $message
);
}
$app->response()->header("Content-Type", "application/json");
echo json_encode($response);
});
The problem I am having is that when the user logs in I set a session variable in the /login function. But when the session variable i set in login function isn't being retrieved in the /user_data function.
Anyone knows whats going on?
Have you started session with session_start() ?
Correct logic to check session is as follows:
if (isset($_SESSION['userid']))
{
// session exists
// do further work
}

Twilio ignoring errors in PHP library

I have a problem. I have set up the Twilio helper library in PHP to send SMS and everything works fine. But I need to do something and I cant figure out how to do it.
Here is the working code:
try {
$errorIds = array(); //user ids array which had broken phones
$count = 0;
foreach($listUsers as $user){
$sms = $service->account->sms_messages->create(
$fromPhone,
$user['phone'], // From user phone array
$message
);
if(!$sms){ //on error push userId in to error array
$count++;
array_push($errorIds, $user['userId']);
} else {
$count=0;
}
if($count>20){ //if 20 errors in row give back errors
$data['results'] = "error";
$data['message'] = "Encountered to many failed messages in row";
$data['error_id_array'] = $errorIds;
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
} catch (Services_Twilio_RestException $e) {
$data['results'] = "error";
$data['message'] = $e->getMessage();
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
Everything works fine. The problem is when an error happens because of a broken phone, the loop which goes through the array breaks and sending stops. I need to keep sending, how could I do this? This is controller and requests is sent from ajax call, thats why there are echo statements!
When exception throws, the foreach loop breaks and execution comes to catch
So make your code as
try {
$errorIds = array(); //user ids array which had broken phones
$count = 0;
foreach($listUsers as $user){
try
{
$sms = $service->account->sms_messages->create(
$fromPhone,
$user['phone'], // From user phone array
$message
);
}
catch (Exception $e)
{ //on error push userId in to error array
$count++;
array_push($errorIds, $user['userId']);
}
if($count>20){ //if 20 errors in row give back errors
$data['results'] = "error";
$data['message'] = "Encountered to many failed messages in row";
$data['error_id_array'] = $errorIds;
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
}
$data['results'] = "success";
$data['message'] = "Your message have been sent successfully";
$data['error_id_array'] = $errorIds;
echo json_encode($data);
} catch (Services_Twilio_RestException $e) {
$data['results'] = "error";
$data['message'] = $e->getMessage();
$data['error_id'] = $user['userId'];
echo json_encode($data);
}
An additional try catch block within foreach loop
Here's the same code but a bit trimmed... This worked for me!
<?PHP
require "Services/Twilio.php";
// Set our AccountSid and AuthToken from twilio.com/user/account
$AccountSid = "{ACCOUNTSID}";
$AuthToken = "{AUTHTOKEN}";
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($AccountSid, $AuthToken);
/* Your Twilio Number or Outgoing Caller ID */
$from = '2126404004';
$people = array("212-716-1130");
$body = "Enter your text message here";
$errorIds = array(); //user ids array which had broken phones
foreach ($people as $to) {
try
{
$client->account->sms_messages->create($from, $to, $body);
echo "Sent message to: $to \n <br>";
}
catch (Exception $e)
{ //on error push userId in to error array
$count++;
array_push($errorIds, $to);
}
}
print_r($errorIds);
?>

Categories