I need a help for avoid duplication entries on my database table using CodeIgniter.
I have a table called “user_course_tbl” with 3 columns as mentioned below.
Id
staff_name
course_code
I need to enter staff name and course code without duplications.
As mentioned in table, same person can add more different course codes. But same person couldn’t add same course code more than 1.
Ex: Smith has more different courses for the table. It will be ok. But Ann has same course more than 1. This should be avoiding. should not have same value for staff_name and course_code columns both together.
I wrote coding for the above matter. But I couldn’t understand to validate this matter.
View
<?php echo form_open_multipart('Course/insert_courses_for_users');?>
<div class="box-body">
<div class="col-md-6">
<div class="form-group">
<label>User</label>
<select id="user" class="form-control" name="user" required>
<option value="">Select</option>
<?php
if(isset($user))
{
foreach($user as $cnt)
{
print "<option value='".$cnt['staff_name']."'>".$cnt['staff_name']."</option>";
}
}
?>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Course Code</label>
<select id="CourseCode" class="form-control" name="courscode" onchange="getcoursename(this.value)" required>
<option value="">Select</option>
<?php
if(isset($coursecode))
{
foreach($coursecode as $cnt)
{
print "<option value='".$cnt['course_code']."'>".$cnt['course_code']."</option>";
}
}
?>
</select>
</div>
</div>
Controller
function insert_courses_for_users()
{
$this->form_validation->set_rules('user', 'User', 'required');
$this->form_validation->set_rules('courscode', 'Course Code', 'required');
$id=$this->input->post('txtid');
$user=$this->input->post('user');
$coursecode=$this->input->post('courscode');
$data=$this->Course_model->insert_courses_for_user(array('id'=>$id,'staff_name'=>$user,'course_code'=>$coursecode));
if($data==true)
{
$this->session->set_flashdata('success', "New Course added for user Succesfully");
}else
{
$this->session->set_flashdata('error', "Sorry, New Course added for user is Failed.");
}
redirect($_SERVER['HTTP_REFERER']);
}
Model
function insert_courses_for_user($data)
{
$this->db->insert("user_course_tbl",$data);
return $this->db->insert_id();
}
Could you please help to solve this matter?
(1)Method:-
In Controller:-
When you define the form validation , add a validator for is_unique
$this->form_validation->set_rules('staff_name', 'Staff Name', 'required|is_unique[user_course_tbl.staff_name]');
(2)Method:-
Search in the database ,the course_code & staff_name before insertion they exsists or not.
Solution 1
$courscode=$this->db->query('select * from user_course_tbl where
courscode='.$this->input->post('courscode'));
if(isset($courscode) && !empty($courscode)) { $is_unique =
'|is_unique[user_course_tbl.courscode]' } else { $is_unique = ''
}
$this->form_validation->set_rules('courscode', 'Course Code',
'required|trim|xs0s_clean'.$is_unique);
$this->form_validation->set_message('is_unique', 'The %s is already
taken, Please use another %s'); // add message for the is_unique
note :use same for staff name.
Solution 2:
$this->form_validation->set_rules('courscode', 'Source Code', 'required|is_unique[user_course_tbl.courscode');
Related
i'm trying to make a custom validation rules for a field. It's a multiple checkbox.
<div class="row checkbox-wrapper" id="checkbox-wrapper">
<?php foreach ($facilities as $facility) : ?>
<div class="col-md-6 mb-2">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="list_facility[]" value="<?php echo $facility['id']; ?>">
<label class="custom-control-label"><?php echo $facility['facility_name'] ?></label>
</div>
</div>
<?php endforeach ?>
</div>
So i try to validate them with a custom rule called facility_valdation()
$this->form_validation->set_rules('list_facility', 'Facility List', 'callback_facility_validation');
public function facility_validation($array)
{
if ($array == NULL) {
$this->form_validation->set_message('facility_validation', 'Fasilitas tidak boleh kosong (minimal = 1)');
return FALSE;
} else {
return TRUE;
}
}
The false condition is correct, whenever i leave the checkbox empty, it returns the message. but if i try to check one or more box, i keep getting the false message.
I've tried to var_dump my list_facility variable and i already get what i want. It is NULL when there are no checkbox checked, or an array of id for every checkbox i checked.
I've implemented the custoiom validation in another controller and it works just fine
Your form input field is array, so your validate field must be an array too. It should be
$this->form_validation->set_rules('list_facility[]', 'Facility List', 'callback_facility_validation');
list_facility[] instead of list_facility
I've tried and it works. Hope this helps
Hello I am inserting data in database. When I insert both category and description then data in inserting but when I don't insert in the category and description input and click on create then no error showing with blank page admin/category/ register_category, I want to show that category and description field should not be empty.
category.php view page is below :
<?php if(isset($_SESSION['success'])){ ?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?>
</div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form class="form" action="<?php echo site_url('admin/category/register_category') ?>" method="POST">
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<label for="contactinput5">Discription</label>
<textarea class="form-control border-primary" type="text" placeholder="discription" name="discription" id="contactemail5"></textarea>
<button type="submit" name="create" class="btn btn-primary">
and my controller Category.php page is:
<?php
class Category extends CI_Controller {
function index() {
$this->load->view('admin/category');
}
function register_category() {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
echo "form validate";
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else{
redirect('admin/category');
}
}
}
}
?>
model categories page:
<?php
class Categories extends CI_Model
{
function validate()
{
$arr['categoryname'] = $this->input->post('category');
$arr['discription'] = $this->input->post('discription');
return $this->db->insert('category',$arr);
}
}
?>
If validation result is not true, you can get errors from $this->form_validation->error_array(), loop the return array and show the error to the user.
Hope this help.
hey guys thanks and i got my answer just by putting this code
if($this->form_validation->run() == FALSE)
{
$this->index();
}
Hello Please update your function in the controller. There is issue in validation condition Changes TURE to FALSE. Check below code.
function register_category()
{
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('category');
}
else
{
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category)
{
$this->session->set_flashdata("success","Your data has been added");
redirect("admin/category","refresh");
}
else
{
redirect('admin/category');
}
}
}
Get all post validation errors in controller :
echo validation_errors();
If you want to show at the end of textbox use this following method :
<label for="contactinput5">Category Name</label>
<input class="form-control border-primary" type="text" placeholder="category" name="category" id="contactinput5">
<?php echo form_error('category', '<div class="error">', '</div>'); ?>
FYI your solution only worked because validation_errors() only applies to the current instance. When you redirect that information is lost. You would have to store it in session variable or this is common (change form action to self or leave blank):
function index() {
if ($_POST) {
$this->form_validation->set_rules('category', 'Category', 'required');
$this->form_validation->set_rules('discription', 'Discription', 'required');
if($this->form_validation->run() == TRUE){
$this->load->model('categories');
$insert_category = $this->categories->validate();
if($insert_category){
$this->session->set_flashdata("success","Your data has been added");
}
}
}
$this->load->view('admin/category');
}
Of course your way works too if you are ok with the url changing.
I want delete user and user role by using checkbox. first check then submit button click. After click, selected user and user_role should be deleted.
got php undefined offset 2 error on line 491
this is my model:
public function add_participation(){
$user = $this->input->post('user');
$role = $this->input->post('role');
$delete = $this->input->post('delete');
for($i=0;$i<count($user);$i++){
if($user[$i] !=""){
$this->db->where('workflow_activity_id',$this->input->post('batch'));
$this->db->where('role_id',$role[$i]);
$this->db->where('user_id',$user[$i]);
$exist = $this->db->get('workflow_participation');
$data = array(
'user_id' => $user[$i],
'role_id' => $role[$i],
'workflow_activity_id' => $this->input->post('batch'),
);
if($exist->num_rows() == 0){
$this->db->insert('workflow_participation',$data);
}else{
$this->db->where('workflow_activity_id',$this->input->post('batch'));
$this->db->where('role_id',$role[$i]);
$this->db->where('user_id',$user[$i]);
$this->db->update('workflow_participation',$data);
}
if($delete[$i] == '1'){ //**error on this line**
$this->db->where('workflow_activity_id',$this->input->post('batch'));
$this->db->where('role_id',$role[$i]);
$this->db->where('user_id',$user[$i]);
$this->db->delete('workflow_participation');
}
}
}
return true;
}
In this view page user and user_role show in drop-down.
This is my view page
<div class="form-group">
<label class="control-label col-md-3">User :</label>
<div class="col-md-8">
<select id="user" name="user[]" class="select form-control">
<option value="" selected="selected">-------</option>
<?php
if(!empty($user)){
foreach($user as $user_result){?>
<option value="<?=$user_result->id;?>" <?php if(!empty($participent) && !empty($participent[1]) && $participent[1]->user_id == $user_result->id){?>selected="selected"<?php }?>><?=$user_result->username;?></option>
<?php }}?>
</select>
</div>
<label class="control-label col-md-3">Role :</label>
<div class="col-md-8">
<select id="role" name="role[]" class="select form-control">
<option value="" selected="selected">-------</option>
<?php
if(!empty($role)){
foreach($role as $role_result){?>
<option value="<?=$role_result->id;?>" <?php if(!empty($participent) && !empty($participent[1]) && $participent[1]->role_id == $role_result->id){?>selected="selected"<?php }?>><?=$role_result->name;?></option>
<?php }}?>
</select>
</div>
<label class="control-label col-md-3">Delete :</label>
<div class="col-md-8">
<input type="checkbox" name="delete[]" value="1">
</div>
Since you are using delete[] as array, i hope your view is in a loop.
a checkbox value is submitted only when it is checked. So you will receive your input in wrong order.
ie, you selected first user and role and checked last delete, you may receive delete for first user. The second and third delete will be undefined. Please see this link for details and hidden field hack for this issue
So I suggest change the following 3 lines in your html as following. you can use $participent[1]->user_id ( or a counter) as index in view file.
<select id="user" name="user[<?php echo $participent[1]->user_id;?>]" class="select form-control">
...
<select id="role" name="role[<?php echo $participent[1]->user_id;?>]" class="select form-control">
...
<input type="checkbox" name="delete[<?php echo $participent[1]->user_id;?>]" value="1">
change the loop from this
for($i=0;$i<count($user);$i++){
to
foreach( $user as $i => $unused ) {
Then instead of equal checking
if($delete[$i] == '1'){ //**error on this line**
use
if( isset($delete[$i]) ){ //**error on this line**
// if( $delete[$i] == '1' ){ //uncomment if you need double confirmation
First check if the variable $role have the same amount of data as $user, if it's not so you have a problem.
Next for the line for($i=0;$i<count($user);$i++), create an outside variable for your count, here everytime you enter the for, the count() is called, bad optimisation.
Clicking on a text displaying that text in url but unable to show that text in view file.
View:
<div class="applynow">Apply Now</div>
Clicking on the apply now button displaying the job name in URL.
But The job name is not dislaying in view file.
Controller:career/apply
function apply()
{
$this->load->model('career_model');
$data['records2']= $this->career_model->getcareerdatas($this->uri->segment(3));
$data['mainpage']='apply';
$this->load->view('templates/template',$data);
}
Career Model:
function getcareerdatas($id)
{
$this->db->select('jobs_list.*');
$this->db->from('jobs_list');
$this->db->where(array('jobs_list.job_name'=>$id));
$q=$this->db->get();
if($q->num_rows()>0)
{
return $q->result();
}
else
{
return false;
}
}
View:
<form name="applynow" id="applynow" enctype="multipart/form-data" method="post" action="<?php echo base_url();?>apply/applynow">
<div class ="applyus">
<?php if(isset($records2) && is_array($records2)):?>
<?php foreach ($records2 as $r):?>
<span class="digit"><?php echo $r->job_name ;?></span>
<?php endforeach;endif;?>
<div class="applyfullname contactname">
<label for="fullname"><font color="black">Full Name</font><span class="mandatory"><font color ="red">*</font></span></label>
<input type="text" class="form-control names" name="fullname" id="fullname " value="<?php echo set_value('fullname');?>" placeholder="Full Name">
<?php echo form_error('fullname', '<div class="error">', '</div>'); ?>
</div>
<div class="applynowemail contactemail">
<label for="email"><font color="black">Email</font><span class="mandatory"><font color ="red">*</font></span></label>
<input type="email" class="form-control emails" id="email" name="email" value="<?php echo set_value('email');?>" placeholder="Email" >
<?php echo form_error('email', '<div class="error">', '</div>'); ?>
</div>
Clicking on apply now button it will open another page in that page it is not displaying the job name.
MYSQL:
+---------+--------------------+--------------------+-----------------+
| jobs_id | job_name | jobs_name | job_description |
+---------+--------------------+--------------------+-----------------+
| 1 | Junior QA Enginner | Junior_QA_Enginner | Description |
| 2 | Junior Engineer | Junior_Enginner | Description |
+---------+--------------------+--------------------+-----------------+
First view is like (take job_id instead job_name in url) :
<div class="applynow">Apply Now</div>
Now, after clicking on this your controller be like (no need of segment, you can take value of querystring as parameter of function in codeigniter) :
function apply($job_id)
{
$this->load->model('career_model');
$data['records2']= $this->career_model->getcareerdatas($job_id);
$data['mainpage']='apply';
$this->load->view('templates/template',$data);
}
Then your model is (change your query to compare with job_id instead job_name) :
function getcareerdatas($id)
{
$this->db->select('jobs_list.*');
$this->db->from('jobs_list');
$this->db->where('jobs_list.jobs_id', $id);
$q = $this->db->get();
return $q->result();
}
Keep the view as it is. If you get matching record with your $jobs_id then you definitely get data in $records2.
Try this solution.
Try this
http://www.codeigniter.com/user_guide/database/results.html
function getcareerdatas($id)
{
$this->db->where('job_name', $id);
$q = $this->db->get('jobs_list');
if($q->num_rows() > 0) {
return $q->result();
} else {
return array();
}
}
Make sure your controller has first letter upper case only.
On controller echo $this->uri->segment(3) make sure you are getting correct
Update
Remove && is_array($records2) just for testing.
<?php if(isset($records2)) {?>
// Other data
<?php }?>
I have select input in my form for manufacturers.
<div class="form-group">
<label for="manufacturer">Manufacturer</label>
<select id="manufacturerSelect" name="manufacturer" class="form-control">
<option disabled selected value> -- select an manufacturer -- </option>
<?php foreach ($manufacturers as $manufacturers_item): ?>
<option value="<?=$manufacturers_item['id'];?>" <?php echo set_select('manufacturer',$manufacturers_item['id'], ( !empty($manufacturer) && $manufacturer == $manufacturers_item['id'] ? TRUE : FALSE )); ?> ><?=$manufacturers_item['name'];?></option>
<?php endforeach; ?>
<option disabled>──────────</option>
<option value="24" <?php echo set_select('manufacturer','24', ( !empty($manufacturer) && $manufacturer == '24' ? TRUE : FALSE )); ?> >Other</option>
</select>
<?php echo form_error('manufacturer'); ?><br />
</div>
If "other" (value == 24) is checked additional input is asked:
$('body').on('change', '#manufacturerSelect', function() {
if ($(this).val() == 24) {
$("#otherManufacturerSelect").removeClass('hidden');
} else {
$("#otherManufacturerSelect").addClass('hidden')
}
});
And HTML:
<div id="otherManufacturerSelect" class="form-group">
<label for="otherManufacturer" >What is it then?</label>
<input type="text" name="otherManufacturer" class="form-control">
<?php echo form_error('otherManufacturer'); ?><br />
</div>
CSS:
.hidden {
display: hidden;
}
Now if user picks "other" as manufacturer addition input is displayed. Form validation rule for otherManufacturer is added in server side if manufacturer == 24. The problem is that the other manufacturer input is displayed every time user get response from server. I could add class="hidden" by default to other manufacturer div but if the form validation doesnt run other manufacturer field will not be displayed again to user.
What I need is PHP IF condition inside:
<div id="otherManufacturerSelect" <?php if(/*???*/):?>class="hidden"<?php endif; ?> class="form-group">
So that class="hidden" would be added only if manufacturer is not "other". but I cannt think of rigth condition.
Any help would be appreciated!
EDIT
Controller:
public function create()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('manufacturer', 'Manufacturer', 'required');
if($this->input->post('manufacturer') == '24'){
$this->form_validation->set_rules('otherManufacturer', 'Other manufacturer', 'required');
}
$data['manufacturers'] = $this->puzzles_model->getManufacturers();
if ($this->form_validation->run() === FALSE)
{
$this->load->view('puzzles/create', $data);
}
else
{
/* do the upload, return upload errors or save in db*/
}
}
In your particular case this would fix the problem:
<div id="otherManufacturerSelect" class="form-group <?php if(isset($manufacturer) && $manufacturer !== '24') { echo 'hidden'; } ?> ">
<label for="otherManufacturer" >What is it then?</label>
<input type="text" name="otherManufacturer" class="form-control">
<?php echo form_error('otherManufacturer'); ?><br />
</div>
Then you can remove the JS snippet. The additional form will be hidden on server side (class="hidden" will be set).
I saw that you're using var $manufacturer in the same template. I can't see your controller and how you're passing variables but instead of $manufacturer you can also use $_GET['manufacturer'] or $_POST['manufacturer'] (depending on your form action method).
Notice: $_GET['manufacturer'], $_POST['manufacturer'] and $_REQUEST['manufacturer'] is NOT sanitized input. When using $manufacturer I assume that it's sanitized in your controller.