I am trying to return a db value using the following function in case of failure the function is supposed to return an error object. I have separated the code block with If/else statement. The if condition satisfies and the if block is executed. But for some reason the return statement in the if block do not execute and the code execution continues to next statement. I tried the two options on both cases the results are same.
First Code
public function is_defined_headtype($head_id)
{
if ($is_defined = $this->ci->account_head_model->is_defined_headtype($head_id))
{
echo "Im here<br>";
return $this->_success($is_defined, ACC_SUCCESS);
}
echo "Im here also";
// General Error Occurred
return $this->_general_error();
}
Second Code
public function is_defined_headtype($head_id)
{
if ($is_defined = $this->ci->account_head_model->is_defined_headtype($head_id))
{
echo "Im here<br>";
return $this->_success($is_defined, ACC_SUCCESS);
}
else
{
echo "Im here also";
// General Error Occurred
return $this->_general_error();
}
}
In both cases I am getting the following output.
Im here
Im here also{"err":1,"code":1,"msg":"Error"}
Calling function definition
public function add_eam($user_id, $eamname, $entityid, $headid, $eamdescription, $eamisfraction, $eampercentage, $eamamount, $affectedheadid)
{
if (/* $eam_id = $this->ci->account_eam_model->insert_eam($user_id, $eamname, $entityid, $headid) */ true)
{
$is_defined = $this->is_defined_headtype(/* $headid */1);
echo json_encode($is_defined);
if($is_defined == 1)
{
echo "Im here";
exit();
if ($entity_id = $this->ci->account_eam_definition_model->insert_eam_definition(/* $user_id */ 1, $eam_id, $eamdescription, $eamisfraction, $eampercentage, $eamamount, $affectedheadid))
{
return $this->_success($eam_id, ACC_ENTITY_ADDED);
}
else
{
return $this->_general_error();
}
}
echo "Im not here";
exit();
return $this->_success($eam_id, ACC_ENTITY_ADDED);
}
// General Error Occurred
return $this->_general_error();
}
hi i think the error is here
you are doing an if statement with only one '=' this is to set a value but you want to comapre so that should be:
'==' to compare that two values are the same
'!=' to see if the two values are different
public function is_defined_headtype($head_id)
{
if ($is_defined = $this->ci->account_head_model->is_defined_headtype($head_id))
{
echo "Im here<br>";
return $this->_success($is_defined, ACC_SUCCESS);
}
echo "Im here also";
// General Error Occurred
return $this->_general_error();
}
In If statement try Type Juggling (int) or use === for strong compare with both side data.
Related
every time I use insert function in my model, the return always true, here's my code
public function insert_text($data)
{
return $this->db->table($this->table)->insert($data);
}
call code
if ($this->text->insert_text($data)) {
echo "success";
} else {
echo "failed";
}
even the execution failed (cause of same primary key already exists), code always return "success", how to fix it?
Thanks
check if inserted successfuly
if ($this->db->insert_id()) {
echo "success";
} else {
echo "failed";
}
I cant get returned value from php function call.
...
$dey=$validate->yoxla($this->ad,$this->soyad,$this->istadi,$this->sifre,$this->email);
if($dey){ // i cant get returned value from here. even it is true.
echo 'asd';
if(!$checkuser->checkusername($this->istadi)){
$err=array();
$err['code']='code14';
$err['aciglama']=$code14;
print json_encode($err);
die();
}elseif(!$checkuser->checkemail($this->email)){
$err=array();
$err['code']='code15';
$err['aciglama']=$code15;
print json_encode($err);
die();
}else{
$err=array();
$err['code']='acig';
print json_encode($err);
die();
}
}
yoxla() function:
...
elseif (!preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $sifre)){
$err=array();
$err['code']='code11';
$err['aciglama']=$code11;
print json_encode($err);
die();
}elseif($email==""){
$err=array();
$err['code']='code12';
$err['aciglama']=$code12;
print json_encode($err);
die();
}elseif (!$this->validEmail($email)) {
$err=array();
$err['code']='code13';
$err['aciglama']=$code13;
print json_encode($err);
die();
}else{
return true;
}
I call first one by ajax request. and there is nothing returning to ajax or i cant get returned value from getresult() function.
Remove () from From class declaration :
try this :
class Form{
public function getresult(){
return true;
}
}
$validate=new Form();
$result=$validate->getresult();
if($result){
echo 'true';
}else{
echo 'false';
}
Enable php error logging so that you could understand such errors on browser : http://php.net/manual/en/function.error-reporting.php
I'm working on an api, it handles the requests which comes from clients, then gets the response from server(developed using codeigniter 3) and forwards that back to client.
But, in case of any database errors, like duplicate id, or null values, the model class cannot handle that error to display a proper error message. I've tried the try catch block but not succeeded yet.
Here's the model:
public function add() {
try {
$this->db->trans_start(FALSE);
$this->db->insert('users', $preparedData);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
throw new Exception("Database error:");
return false;
}
return TRUE;
} catch (Exception $e) {
log_message('error: ',$e->getMessage());
return;
}
}
One thing to mention, I've set db_debug to FALSE.
Any help would be appreciated.
As for CI 3, below code gets database error code and error message. db_debug is set to FALSE.
public function add() {
try {
$this->db->trans_start(FALSE);
$this->db->insert('users', $preparedData);
$this->db->trans_complete();
// documentation at
// https://www.codeigniter.com/userguide3/database/queries.html#handling-errors
// says; "the error() method will return an array containing its code and message"
$db_error = $this->db->error();
if (!empty($db_error)) {
throw new Exception('Database error! Error Code [' . $db_error['code'] . '] Error: ' . $db_error['message']);
return false; // unreachable retrun statement !!!
}
return TRUE;
} catch (Exception $e) {
// this will not catch DB related errors. But it will include them, because this is more general.
log_message('error: ',$e->getMessage());
return;
}
}
Refer to documentation at https://www.codeigniter.com/userguide3/database/queries.html#handling-errors
saying
If you need to get the last error that has occurred, the error() method will return an array containing its code and message.
It is a bit incomplete in my opinion because it does not show error code and error message in the example code.
I just lost an hour trying to figure out why I can't get the error in my code. You have to check for an error after each statement! Working solution:
function insertUpdate($data) {
$order = $data->order;
$order_products = $data->order_products;
$this->db->trans_start();
$order->user_id = $this->session->user_id;
$error = "OK";
if (!$this->db->insert('_order', $order)) {
$error = $this->db->error()["message"];
}
$id = $this->db->insert_id();
foreach ($order_products as $row) {
$row->order_id = $id;
if (!$this->db->insert('_order_product', $row)) {
$error = $this->db->error()["message"];
break;
}
}
$order_code = substr(md5($id), 0, 6);
if (!$this->db->where('order_id', $id)) {
$error = $this->db->error()["message"];
}
if (!$this->db->update('_order', ["order_code" => $order_code])) {
$error = $this->db->error()["message"];
}
$this->db->trans_complete();
return [
'result' => $error, 'order_code' => $order_code
];
}
Suggestion in above code
Remove line $this->db->trans_complete();
If we see $this->db->error() after completing transaction it will be always empty
Remove semicolon - log_message('error :',$e->getMessage());
return;
public function add()
{
try {
$this->db->trans_start(FALSE);
$this->db->insert('users', $preparedData);
// documentation at
// https://www.codeigniter.com/userguide3/database/queries.html#handling-errors
// says; "the error() method will return an array containing its code and message"
$db_error = $this->db->error();
if (!empty($db_error)) {
throw new Exception('Database error! Error Code [' . $db_error['code'] . '] Error: ' . $db_error['message']);
return false; // unreachable return statement !!!`enter code here`
}
return TRUE;
} catch (Exception $e) {
// this will not catch DB related `enter code here`errors. But it will include them, because this is more general.
log_message('error ',$e->getMessage());
return;
}
}
Below are details:
1. PDO connect class which have the function to connect with DB. Say PDO_connect class.
2. Logic class file say MyLogic file, MyLogic file include PDO_connect and another class in which functions are written say MyFunction Class.
Problem :
I am not able execute select query and fetch object using below query.
MyFunction Class have function :
function gCD($query_type,$connection_obj,$u_id,$c_id)
{
if($query_type == 'SELECT')
{
$prepare_sql = $connection_obj->prepare("SELECT c_n from cs where u_id=:u_id and c_id=:c_id");
$query_select_clients = $prepare_sql->execute(array(':u_id'=>$u_id,':c_id'=>$c_id));
echo "\n".$prepare_sql->rowCount();
exit; //This is also not working.
$g_c_obj = $prepare_sql->fetch(PDO::FETCH_OBJ);
var_dump($g_c_obj);
}
}
All arguments are passed from MyLogic File, connection and other details.
If I do this debugging it returns true:
var_dump($prepare_sql->execute(array(':u_id'=>$u_id,':c_id'=>$c_id)))
But neither rowCount() nor fetch() are giving any output. Your help is highly valuable.
This information was too long for a comment so I am typing this as an answer to help debug your case.
Test each case as you go through using PDO functionality. Each functionality like prepare, execute and fetch have a return value. Capture the return value, analyze it and act based on the return value. Substitute your information in appropriate places and see where your execution path stops.
<?php
$db = new PDO('mysql:host=localhost;dbname=xyz', 'user', 'pass');
gCD('SELECT', $db, 2, 2);
function gCD($query_type,$connection_obj,$u_id,$c_id)
{
if($query_type == 'SELECT')
{
try
{
$prepare_sql = $connection_obj->prepare("SELECT c_n from cs where u_id=:u_id and c_id=:c_id");
if ($prepare_sql === false)
{
echo "PDO prepare failed\n";
return false;
}
$query_select_clients = $prepare_sql->execute(array(':u_id'=>$u_id,':c_id'=>$c_id));
if ($query_select_clients === false)
{
echo "PDO execute failed\n";
return false;
}
echo "\n".$prepare_sql->rowCount();
$g_c_obj = $prepare_sql->fetch(PDO::FETCH_OBJ);
if ($g_c_obj === false)
{
echo "PDO fetch failed\n";
return false;
}
var_dump($g_c_obj);
return true;
}
catch (Exception $e)
{
echo 'Exception: ', $e->getMessage(), "\n";
}
}
else
{
echo 'Not a select statement', "\n";
}
return false;
}
?>
I have a php file(register.php) with a public function register($data) where errors are validated.Then errors are counted and if no errors are found, validation is passed.
register.php:
class ARegister {
public function register($data) {
$user = $data['userData'];
//validate provided data
$errors = $this->validateUser($data);
if(count($errors) == 0) {
//first validation
}
}
public function validateUser($data, $botProtection = true) {
$id = $data['fieldId'];
$user = $data['userData'];
$errors = array();
$validator = new AValidator();
if( $validator->isEmpty($user['password']) )
$errors[] = array(
"id" => $id['password'],
"msg" => Lang::get('password_required')
);
return $errors;
}
The problem is, that I need to get this confirmation of validated data to my other php file (othervalidation.php) where I've made another validation:
othervalidation.php:
<?php
require 'register.php';
if ( !empty($action) ) {
switch ( $action ) {
case 'process_payment':
try {
$instance = new ARegister();
if($instance->validateUser($data, $errors)) {
throw new Exception('Validation error');
}
} catch (Exception $e) {
$status = false;
$message = $e->getMessage();
}
}
How can I send the result of $errors variable to my other validation (othervalidation.php)?
I looked at your new code design and here's the new problems I found.
First, in your register function, you use the errors variable as an integer while your validate function returns an array. You got two possibilities here.
You can change your register method to check out if your error array is empty like this:
if(empty($errors)) {
//first validation
}
Count is also valid, but I still prefer empty since it's syntactically clearer. Furthermore, the count function returns 1 if the parameter is not an array or a countable object or 0 if the parameter is NULL. As I said, it is a functional solution in your current case but, in some other contexts, it might cause you unexpected results.
Here in your method declaration, I see that you are expecting a boolean (botProtection).
public function validateUser($data, $botProtection = true) {
But you are supplying an errors parameter
if($instance->validateUser($data, $errors)) {
You don't provide me the declaration of the errors variable, but it is probably not matching the bot protection parameter your function is expecting. PHP is using lose typing, it is useful but, once again, you got to be careful for bugs hard to find. For public function, you should always make sure a way or another that the supplied parameter won't lead to code crash.
In your code, the data parameter seems to be an array. You can use parameter hinting to force the use of array like this:
public function register(array $data) {
public function validateUser(array $data, $botProtection = true) {
And even specific class (as if you where using "instance of" in a condition)
public function register(MyDataClass $data) {
public function validateUser(MyDataClass $data, $botProtection = true) {
Also, you're not even using the botProtection parameter in your validateUser method.
On the same function call:
if($instance->validateUser($data, $errors)) {
you are expecting a Boolean (true or false), but the method returns an array. If you want to use the code the way it is currently designed, you must use it like this
if(!empty($instance->validateUser($data, $errors)) {
Here, I'm not so sure it is necessary to use exception. Ain't it be easier to design your code like this?
if(!empty($instance->validateUser($data, $errors)) {
$message = 'Validation error';
}
In your validate function, is the "isEmpty" function also validating if the client provided a password?
If that's the case you could validate it like this:
if(!in_array($user['password']) or empty($user['password']))
With those corrections, your code should be functional.
Here's a sample of how I would had design your code (considering the code sample provided):
class ARegister {
public function register($data) {
$user = $data['userData']; //don't declare it here, all the user validations must be done in validateUser($data, &$errors)
$errors = array();
if($this->validateUser($data, $errors)) {
//first validation
}
}
/**
* Note: If you are not returing more than one error at the time, $errors should be a string instead of an array.
*/
public function validateUser($data, array &$errors) {
$isValid = false;
if (in_array($data['fieldId']) and in_array($data['fieldId']['password']) and in_array($data['userData'])){
if(!in_array($data['userData']['password']) or empty($data['userData']['password'])){
$errors[$data['fieldId']['password']] = Lang::get('password_required');
}
else{
$isValid = true;
}
}
else{
//an invalid data array had been provided
}
return $isValid;
}
For the next part, if the code is executed directly in the view and you are a beginner, create a procedural external controller file (all functions will be public...). If you are a professional, you MUST create a class to encapsulate the treatment.
You must not do treatment directly in the view. The view is a dumb placeholder for data presentation and collecting client's input. The sole action it must do is display the data sent by the controller and send back the client's input to the controller.
The treatment on data is the controller responsibility.
if (!empty($action) ) {
$errors =array();
switch ( $action ) {
case 'process_payment':
$instance = new ARegister();
if($instance->validateUser($data, $errors)) {
//the user is valid, do the treatment
}
else
PageManager::dispayError($errors);
}
unset($instance);
}
}
Here's an example how you can centralize your error display
/**
* Can be more complexe than that, but I'm at my father's home at four hundred kms away from Montreal right now..
*/
public static function dispayError($errors, $size = 4){
if (is_numeric($size)){
if ($size < 0){
$size = 1;
}
elseif($size > 5){
$size = 5;
}
}
else{
$size = 4;
}
if (is_scalar($errors)){
echo '<h' . $size . 'class="ERROR_MESSAGE">' . $errors . '</h' . $size . '><br>';
}
elseif (is_array($errors)){
foreach ($errors as $error){
if (is_scalar($error)){
echo '<h' . $size . 'class="ERROR_MESSAGE">' . $error . '</h' . $size . '><br>';
}
}
}
}
Of course, you can also support many kind of message:
public static function dispayError($errors, $size = 4){
self::displayMessage("ERROR_MESSAGE", $errors, $size=4);
}
private static displayMessage($class, $messages, $size=4)
Well, took me two hours to write that. I hope you have now enough material to build an efficient, reusable and, no less important, safe code design.
Good success,
Jonathan Parent-Lévesque from Montreal
You can try something like this:
class ARegister {
private $error = 0;
public function register($data) {
if (!$this->validateUser($data)){
$this->error++;
}
}
public function getErrorCount(){
return $this->error;
}
public resetErrorCount(){
$this->error = 0;
}
Or pass the error by reference:
public function register(&$error, $data) {
if (!$this->validateUser($data)){
$error++;
}
}
Personally, I would do all the validation in the same method (in the class for encapsulation), use an error message parameter (passed by reference) to return why the validation failed and use the return statement to return true or false.
class MyClass{
public function validation(&$errorMessage, $firstParameter, $secondParameter){
$success = false;
if (!$this->firstValidation($firstParameter)){
$errorMessage = "this is not working pal.";
}
elseif (!this->secondeValidation($firstParameter)){
$errorMessage = "Still not working buddy...";
}
else{
$success = true;
}
return $success;
}
private function firstValidation($firstParameter){
$success = false;
return $success;
}
private function secondeValidation($secondParameter){
$success = false;
return $success;
}
}
In your other file:
<?php
$instance = new MyClass();
$errorMessage = "";
if ($instance->validation($errorMessage, $firstParameter, $secondParameter)){
echo "Woot, it's working!!!";
}
else{
echo $errorMessage;
}
?>
Is one of these code solutions fit your needs?
Jonathan Parent-Lévesque from Montreal