Codeigniter: How to handle database error? - codeigniter

I'm creating a web application using codeigniter and postgresql. I have this inside my database:
user
id name
unique(name)
When someone try to register with the same name, i get an error. How can i handle them, without displaying the codeigniter's error and showing instead my custom error?
If i set $db['default']['db_debug'] = FALSE; i don't get any error of course, but is there a way to handle the db error or should i check myself if the table already contains an entry with that same name?

Use Codeigniters form validation class. is_unique[table.columnName]. This will do the work for you. Below is an example
$this->form_validation->set_rules('name', 'Name', 'is_unique[table_name.Name]');
Then just set a custom message referencing the is_unique validation like below
$this->form_validation->set_message('is_unique', 'Name already exists');

I dont know anything by codeigniter, but im going to assume the principle works the same:
You first make a query like SELECT id FROM tablename WHERE name='SomeName' LIMIT 1, then you check the number of rows. This kind of checking is fairly normal. Control as much as you (sensebly) can to avoid errors down the road.
Zero rows? Safe to insert. Not zero rows? Display something like 'username allready taken'.
Example with some code:
$check = mysqli_query("SELECT id FROM tablename WHERE name='SomeName' LIMIT 1");
if( $check->num_rows!==0 ){
echo 'Username allready taken'; // echo is bad, you should process this better, but this is easy demo
}
else{
// Your normal inserting code goes here.
}

Like Martijn said, it is a solution.
CI doesn't throw exception, so when you perform a query, it will return NULL if the statement fails.
You may want to see CodeIgniter - how to catch DB errors?

Related

How to use Script to set a Netsuite System Field as Mandatory?

I have a Client Suitescript 2.0 that handles some logic on fieldChanged for Sales Order records.
This includes setting some fields as mandatory/non-mandatory according to certain criteria.
It works perfectly, except when I attempt to set a Netsuite System field (such as 'memo') as mandatory/non-mandatory.
Nothing happens, and no error.
The code used on all fields is context.currentRecord.getField({fieldId: 'memo'}).isMandatory = true;
Does anyone know why this issue would occur, or know of any workaround?
Many thanks!
Giles
try this
var memo = context.currentRecord.getField({fieldId: 'memo'});
memo.isMandatory = true;

I want to check duplication value during insert time without using unique keyword

i make one table for with some column with nullable.
i already tried with two different query. one using
Register_member::where('passport',$passport)->orWhere('adharcardnumber',$adharcardnumber)->get();
and second DB::table type query.
$row = Register_member::where('passport',$passport)->orWhere('adharcardnumber',$adharcardnumber)->get();
if (!empty($row))
{
return response()->json(["status"=>0, "message"=>"Adharcard or Paasport number already exit."]);
}
if (empty($row))
{
Register_member::insert(['first_name'=>request('first_name'), 'middle_name'=>request('middle_name'), 'last_name'=>request('last_name'), 'adharcardnumber'=>request('adharcardnumber'), 'ocipcinumber'=>request('ocipcinumber'), 'passport'=>request('passport'), 'birthday'=>request('birthday'),
'mobilecode'=>request('mobilecode'), 'mobilenumber'=>request('mobilenumber'), 'email'=>request('email'), 'address'=>request('address'), 'landmark'=>request('landmark'), 'area'=>request('area'),
'gender'=>request('gender'), 'pincode'=>request('pincode'), 'city_name'=>request('city_name'), 'state_id'=>request('state_id'), 'country_id'=>request('country_id'), 'sampraday'=>request('sampraday'), 'other'=>request('other'), 'sms'=>request('sms')]);
return response()->json(["status"=>1, "message"=>"Member register successful."]);
}
if adharcardnumber or passport number are exists in table, then nagetive response. if in both any one in unique then, insert data in table
Let me suggest you something which I think serve you as a good solution. You can use the unique with required and regex. In this way it will use the already recommended ways of Laravel which are the best.
As an example for your adhaar card,
the validation should look like this
$request->validate([
'adhaar ' =>['required','unique:users','regex:/\d{12}/'],
]);
where adhar is the filed name where adhaar number is entered. Be sure to use validator like this use Illuminate\Support\Facades\Validator;. Also $request is the instance of the Request.
Using the required prevent empty field submission and the regex will throw an error if the pattern is not matched completely. so I think it would be a better a way to handle the scenario.
the above solution will work in both adhaar and passport. But for the passport the regex will be different though.
Please note these are all demo examples, you might need to modify it according to your needs. I use https://www.phpliveregex.com/ for regex making and checking and it is good enough.
I hope you get an idea of how to begin but if you need more information then let me know in the comments.

Laravel 5.4 : Dynamic validation rule

I kind of struggle to find the answer to my question, and my test don't prove to be useful. So maybe someone here would have hit the same issue that I'm facing.
I have inputs with the following kind of patterned name projects-0-1, project-0-2, project-1-0 and so on... These are file inputs so people can upload a document/an image.
So basically, I've been trying to get a validation message that would (ideally) be something like that:
$validator->getMessageBag()->add('project-*-*', 'File is empty!');
OR
$validator->getMessageBag()->add('project-*', 'File is empty!');
I tried a couple of things already and nothing seems to work.
The reason I get to add a custom message is that file is simply not validated if it comes empty to the $request object. So I first need to check if the $request->hasFile and in case it doesn't I want to add the error message.
Things to consider:
inputs can be dynamically added to the form, so I don't know the exact number of file inputs I need to validate beforehand.
even if this should not impact the code and validation, it's worth noticing that everything happens through ajax as I embed the form on another website. Therefore I created endpoints etc...
Any hint ?
Right, coming back here in case someone faces that issue too. I found a "hacky" way to get there and it does the trick for me.
As each input file is dynamically added to the DOM, I add an extra hidden input that holds the name of the file input as a value.
Then in my controller I do smth like that:
public function createValuesKeyArray ($preset)
{
$regexPattern = '/^'. $preset .'-[0-9]*$/';
$customPresets = preg_grep($regexPattern, array_keys(Input::all()));
$keys = [];
foreach ($customPresets as $customPreset) {
array_push($keys, $customPreset);
}
return $keys;
}
// This allows me to get all hidden input names in an array in order to get its value from the $request
$hiddenInputs = $this->createValuesKeyArray('hidden-project-name');
Once I get this array, I can do stuff like that and dinamycally add my set of rules for the input files present in the DOM:
foreach($hiddenInputs as $hiddenInput){
$globalRules[$request[$hiddenInput]] = 'required';
}
Not sure if this the right way to get there, but it does the job for me and I don't find that code horrible. I'll stick with it until I find a better way.

Undefined index: quantity

I am having a small problem updating my cart because of "undefined index:quantity message coming up on my text box.On the last line of my code. what is wrong with the code? Any kind consideration will be highly appreciated.
function edit_quantity(){
if(isset($_POST['update_cart'])){
$quantity=$_POST['quantity'];
$sql3="UPDATE Shopcart set qty='$quantity'";
$sql3_run=mysqli_query($conn,$sql3);
$_SESSION['quantity']=$quantity;
$total=$total*$quantity;
}
echo $_SESSION['quantity'];
}
i see you dont have session_start();
put it somewhere before you use $_SESSION
edit:
your code might not enter the if block and would not set the quantity session. That's why you are having an Undefied index error move the echo statement inside the if block so that it will echo when your quantity session is set.
This error is because the POST data does not have a quantity value. You are only checking for an update_cart post value before proceeding to update the session.
As others have mentioned, there is also a serious sql injection problem with your code which you should fix.

Extending ion auth to only allow registrations from certain email addresses/domains

I want to extend Ion Auth to only allow certain email addresses to register.
I'm fairly sure I could hack this together and get something working, but as a newbie to codeigniter and ion auth I wish to find out if there is a "proper way" to be doing what I need?
For instance can I "extend" ion auth (so I can update ion auth core files without writing over my changes?).
I noticed there are also hooks including this one (in the register function):
$this->ci->ion_auth_model->trigger_events('pre_account_creation');
Where do these resolve and can I use this one in order to intercept registrations from email addresses which don't match a list of those I wish to register?
If so, how would I do it? I would need access to the $email variable from the register() function.
Or is it just a case of altering the base code from ion auth and not updating it in the future?
Thanks for any help you can give me. Don't worry about the email bit, I'm capable of working out whether an email address matches the required email domains, I'm more interested in what is the best way to go about extending the library.
Tom
EDIT: Hi Ben, thanks for your answer, and thanks for taking the time to have a look at my issue. Unfortunately this hasn't helped.
I guess what you're trying to do there is add a little bit to the sql query a "where in" clause? I guess that the where in bit is incorrect as there isn't a column name.
Also, at this point I can't modify the sql query satisfactorily to produce the required output. e.g. I can add a hook to a function which is literally $this->db->where('1=1') and this outputs this sql in the next query:
SELECT COUNT(*) AS `numrows` FROM (`users`) WHERE `1=1` AND `email` = 'rawr#rawr.com'
The AND email = 'rawr#rawr.com' bit will always still return no rows. It should be OR email = 'rawr#rawr.com', but without editing the Ion Auth core code then I won't be able to change this.
I am starting to suspect (from the last couple of hours of tinkering) that I may have to edit the ion auth core in order to achieve this.
Check out this example: https://gist.github.com/2881995
In the end I just wrote a little form_verification callback function which I put in the auth controller of ion_auth which checked through a list of allowed domains. :)
When you validate your form in the auth controller you add a callback:
$this->form_validation->set_rules('email', 'Email Address', required|callback_validate_email');
You create a method in the controller called validate_email:
function validate_email() {
if (strpos($this->input->post('email'), '#mycompany.com') === false) {
$this->form_validation->set_message('validate_email', 'Not official company email address.');
return false;
} else return true;
}
This will cause the creation of the user to fail, since all rules must pass. You also provide an error message. Just make sure to have this line on the form view side:
echo validation_errors();

Resources