How do i retrieve the value of dropdown when editing in codeigniter - php

OK, so I have looked everywhere for a solution to my problem but found none so far.My code looks like this.I have created a dynamic view page in which edit and add views are loaded dynamically.But the problem arises when i try to retain the value of select dropdown during editing.I would be grateful if someone could help me out.
View
<div class="panel-body">
<div class="row">
<div class="col-lg-6">
<?php if(#$patient_info){
echo '<h1 class="page-header">Edit Patient</h1>';
}else{
echo '<h1 class="page-header">Add Patient</h1>';
}
?>
<?php if($this->session->flashdata('error')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('error'); ?></div>
<?php } ?>
<?php if($this->session->flashdata('erroredit')){ ?>
<div class="alert alert-danger"><?php echo $this->session->flashdata('erroredit'); ?></div>
<?php } ?>
<?php //echo validation_errors('<div class="alert alert-danger">','</div>'); ?>
<form role="form" method="post" action="<?php echo isset($patient_info) ? site_url('home/patient/edit') .'/' .$patient_info->patientID : site_url('home/patient/new'); ?>">
<div class="form-group">
<?php echo form_error('pname', '<div class="alert alert-danger">', '</div>'); ?>
<label for="pname">Patient Name</label>
<input class="form-control" placeholder="Enter Patient Name" name="pname" value="<?php echo isset($patient_info) ? $patient_info->patientName : ''; ?>">
</div>
<!-- Dropdown menu for selecting clinic -->
<div class="form-group">
<label for="select">Select Clinic Name</label>
<select class="form-control" name="selectClinic">
<option value="none">Select Clinic Below</option>
<?php foreach($allclinic as $key=>$clinic){ ?>
<!--<?php //foreach($clinicByPatient as $clin): ?>-->
<option value="<?php $clinic->clinicID; ?>"
<?php if(isset($patient_info)){
echo 'selected="selected"';
}
?>
>
<?php echo $clinic->clinicName; ?>
</option>
<?php //endforeach; ?>
<?php } ?>
</select>
</div>
<!-- Select Clinic ends-->
<div class="form-group">
<label for="select">Select Dentist</label>
<select class="form-control" name="selectDentist">
<option value="">Select Dentist</option>
<?php foreach($dentistdet as $key=>$dentist){ ?>
<option value="<?php echo $did = $dentist->dentistID;?>"><?php echo $dentist->dentistName; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary btn-lg btn-block" name="submit" value="<?php echo isset($patient_info) ? 'Update Patient' : 'Add Patient'; ?>" >
</div>
</form>
<div class="form-group">
<input type="submit" class="btn btn-danger btn-lg btn-block" value="Cancel">
</div>
Edit controller
public function edit(){
$id = $this->uri->segment(4);
$this->load->library('form_validation');
$this->load->model('clinic_model');
$this->load->model('dentist_model');
$data['patient_info'] = $this->patient_model->getPatientById($id);
$data['clinicByPatient'] = $this->patient_model->getPatientByClinic();
$data['allclinic'] = $this->clinic_model->getAllClinics();
// $data['clinicdet'] = $this->patient_model->getPatientByClinic();
if($_POST){
$this->form_validation->set_rules('pname', 'Patient Name', 'trim|required|xss_clean');
$this->form_validation->set_rules('paddress', 'Patient Address', 'trim|required|xss_clean');
$this->form_validation->set_rules('pcontact', 'Patient Contact', 'trim|required|xss_clean');
if($this->form_validation->run()== FALSE){
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout', $data);
}else{
$patientname = $this->input->post('pname');
$patientaddress = $this->input->post('paddress');
$patientcontact = $this->input->post('pcontact');
$select = $this->input->post('selectClinic');
$option = $this->input->post('selectDentist');
$edited = $this->patient_model->editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option);
if($edited){
$this->session->set_flashdata('successedit', 'Successfully updated the record');
redirect('home/patient');
}
}
}else{
$data['subview'] = 'patient/patient_new';
$this->load->view('includes/layout',$data);
}
}
Model looks like this
<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
class Patient_model extends CI_Model{
public function countPatients(){
$countPatient = $this->db->count_all('patient');
return $countPatient;
}
public function getallpatients(){
$query = $this->db->get('patient');
if($query->num_rows()>0){
return $query->result();
}
else{
return FALSE;
}
}//getallpatients function ends
public function getPatientByClinic(){
$this->db->select('*');
$this->db->from('patient');
$this->db->join('clinic', 'patient.clinicID = clinic.clinicID', 'left');
$this->db->join('dentist', 'patient.dentistID = dentist.dentistID', 'left');
$query = $this->db->get();
if($query->num_rows>0){
return $query->result();
}
}
public function addPatientByClinic($patientname, $patientadd, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientadd,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
return $this->db->insert('patient',$data);
}// method ends
public function deletePatient($id){
$verifyID = array('patientID' => $id);
// $affRows = $this->db->affected_rows();
// $obj = new Patient_model;
if($verifyID){
$this->db->where($verifyID);
$this->db->delete('patient');
if($this->db->affected_rows()){
return TRUE;
}
}
}
public function editpatient($id, $patientname, $patientaddress, $patientcontact, $select, $option){
$data = array(
'patientName' => $patientname,
'patientAddress' => $patientaddress,
'patientContact' => $patientcontact,
'clinicID' => $select,
'dentistID' => $option
);
$query = $this->db->where('patientID', $id)
->update('patient', $data);
if($query){
return true;
}
}//method ends
public function getPatientById($id){
$query = $this->db->where('patientID', $id)
->get('patient');
return $query->row();
}
}//class ends
?>

In the code for your select box, you aren't actually echoing $clinic->clinicID. Thus, when the form is submitted, the value will be empty.
You also need to be careful with how you are choosing which select element will be selected by default - you aren't comparing with anything that will change within the loop. Should you be checking against $clinic->clinicID?

Related

get option values from database codeigniter

I have a php form where I want to select options for a field Email from a list of values saved in a table emailaddress in the database. The table emailaddress has 2 fields 1. idemailaddress and 2. emailaddress, but I am still getting error trying to pull data, please help
Agreement_ctrl
$data['department_list'] = $this->Main_model->get_department_list();
$data['unit_list'] = $this->Main_model->get_unit_list();
$data['terms'] = $this->Main_model->get_terms_list();
$data['emailaddress_list'] = $this->Main_model->get_emailaddress_list();
$data['managers_list'] = $this->Main_model->get_managers_list();
$data['mtnlocation_list'] = $this->Main_model->get_mtnlocation_list();
$data['institution_list'] = $this->Main_model->get_institution_list();
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('gender', 'Gender', 'alpha|xss_clean');
$this->form_validation->set_rules('department', 'Department');
$this->form_validation->set_rules('unit', 'Unit', 'numeric|xss_clean');
Main Model File
}
function get_emailaddress_list()
{
$this->db->order_by('emailaddress', 'ASC');
$query = $this->db->get('emailaddress');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$result [$row->id] = $row;
}
return $result;
}else{
return FALSE;
}
}
Form Page
<div class="form-group row">
<label class="col-sm-3 col-form-label" for="Email">Email Address:</label>
<div class="col-sm-9">
<select name="Email" class="Email form-control" id="Email">
<option value="" <?php echo set_select('Email', ''); ?> >-Select-</option>
<?php if($emailaddress_list){
foreach($emailadress_list as $emailaddress){ ?>
<option value="<?php echo $emailadress->idemailaddress?>" <?php echo set_select('Email', $emailaddress->idemailaddress); ?>><?php echo $emailaddress->emailaddress?></option>
<?php }
}?>
</select>
</div>
</div>
You don't need the foreach loop in your model, just return the query result.
function get_emailaddress_list(){
$this->db->order_by('emailaddress', 'ASC');
$query = $this->db->get('emailaddress');
$data = ($query->num_rows())? $query->result():false;
return $data;
}
Then you loop through this results in your view to create the select options:
<select name="Email" class="Email form-control" id="Email">
<?php if($emailaddress_list):?>
<option value="" disabled selected>-Select-</option>
<?php foreach($emailadress_list as $row): ?>
<option value="<?=$row->idemailaddress?>">
<?=$row->emailaddress?>
</option>
<?php endforeach;?>
<?php else:?>
no records found
<?php endif;?>
</select>

convert array object from database to string

I'm currently coding a blog to get experience with php.
In the edit.php I want to give the category of a post if a post has one.
This is the edit.php:
<div class="categories-heading">
<?php if (!empty($entry->c_Id)): ?>
<div class="category-heading">
<h3>Category: <?php echo e($categoryFromId); ?></h3>
</div>
<div class="category-heading">
<h3>change category</h3>
</div>
</div>
<form method="post">
<div class="categories-post-edit">
<?php foreach($categories as $cat): ?>
<div class="category-post-edit">
<input type="radio" name="category" value="<?php echo e($cat->id); ?>">
<label> <?php echo e($cat->category); ?></label>
</input>
</div>
<?php endforeach; ?>
</div>
</form>
<?php else: ?>
<div class="category-heading">
<h3>choose category</h3>
</div>
</div>
<form method="post">
<div class="categories-post-edit">
<?php foreach($categories as $cat): ?>
<div class="category-post-edit">
<input type="radio" name="category" value="<?php echo e($cat->id); ?>">
<label> <?php echo e($cat->category); ?></label>
</input>
</div>
<?php endforeach; ?>
This is the part of the function edit() in the PostsAdminController.php which is relevant for this:
if(!empty($_POST['title']) AND !empty($_POST['subheading']) AND
!empty($_POST['content'])
AND !empty($_POST['category'])) {
$entry->title = $_POST['title'];
$entry->subheading = $_POST['subheading'];
$entry->content = $_POST['content'];
$entry->c_Id = $_POST['category'];
$this->postsRepository->update($entry);
$savedSuccess = true;
}
$categoryFId = $this->categoryRepository->oneCategory($entry->c_Id);
$categoryFromId = $categoryFId['category'];
var_dump($categoryFromId);
$this->render("post/admin/edit", [
'entry' => $entry,
'savedSuccess' => $savedSuccess,
'categories' => $categories,
'categoryFromId' => $categoryFromId
]);
}
And this is the function oneCategory in the CategoryRepository.php that interacts with the database.
public function oneCategory($id)
{
$table = $this->getTableName();
$model = $this->getModelName();
$stmt = $this->pdo->prepare("SELECT `category` FROM `$table`
WHERE id = :id");
$stmt->setFetchMode(PDO::FETCH_CLASS, $model);
$oneCategory = $stmt->fetch(PDO::FETCH_CLASS);
return $oneCategory;
}
oneCategory() gives out an array no matter if I put SELECT * or SELECT category in the query, that's why I put $categoryFId['category'] into a variable after.
It works, but I think there must be a more easy or quicker way (like special functions or so), I just didn't manage to find what I search for

CODEIGNITER: Check if exist

I have table ingredient w/c consist of(ingredient_id,name),category w/c consist of(category_id,name) and category_ingredients w/c consist of(ingredient_id,category_id). I created a form for adding many ingredients by category and It check if 1 or more ingredients already exists in that category then I will only have to get the id's of the ingredient and then the other ingredients that don't exist will be inserted in my DB. Please help me i really need your help :(
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients(){
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
foreach (explode(',', $this->input->post('ingredient_category')) as $key => $value)
{
foreach ( $ingredient_id as $key => $str ){
$joinData[] = array(
'ingredient_id' => $str,
'category_id' => intval($value)
);
}
$this->products_model->saveCategoryIngredients($joinData);
redirect('dashboard/add_ingredients');
}
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;
}
public function getIngredientByName($name) {
$this->db->select('ingredient_id');
$this->db->limit(1);
$this->db->where('category_id', $category_id);
$ingredientQuery = $this->db->get('category_ingredient');
$ingredient_id = $ingredientQuery->row()->ingredient_id;
$this->db->select('name');
$this->db->where('ingredient_id', $ingredient_id);
$query = $this->db->get('ingredient');
foreach($query->result() as $row)
{
return $row->name;
}
}

Wordpress Post not getting updated in editor

I was building a custom plugin for one of my project and I am facing this issue with custom fields that I have created, but once I was trying to save the fields. I am not getting the data displayed in the admin editor. screenshot of issue page
I am adding the code below Please find it.
<?php
function apt_add_fields_metabox()
{
add_meta_box(
'apt_college_fields',
__('College Fields'),
'apt_college_fields_callback',
'college',
'normal',
'default'
);
}
add_action('add_meta_boxes','apt_add_fields_metabox');
//Display Fields Metabox Content
function apt_college_fields_callback($post)
{
wp_nonce_field(basename(__FILE__),'wp_college_nonce');
$apt_college_stored_meta = get_post_meta($post->ID);
?>
<div class="wrap college-form">
<div class="form-group">
<label for="issue_check"><?php esc_html_e('Issue Date Available','apt_domain'); ?></label>
<select name="issue_check" id="issue_check">
<?php
$option_value = array('Yes','No');
foreach($option_value as $key => $value)
{
if($value == $apt_college_stored_meta['issue_check'][0])
{ ?>
<option selected><?php echo $value; ?></option>
<?php
}
else
{
?>
<option ><?php echo $value; ?></option>
<?php
}
}
?>
</select>
</div>
<div class="form-group">
<label for="college-details"><?php esc_html_e('College Details','apt_domain'); ?></label>
<?php
$content = get_post_meta($post->ID,'college-details',true);
$editor = 'college-details';
$settings = array(
'textarea_rows' => 5,
'media_buttons' => true
);
wp_editor($content,$editor,$settings);
?>
</div>
<div class="form-group">
<label for="application_date"><?php esc_html_e('Application Available Date','apt_domain'); ?></label>
<input type="date" name="application_date" id="application_date" value="<?php if(!empty($apt_college_stored_meta['application_date'])) echo esc_attr($apt_college_stored_meta['application_date'][0]); ?>" />
</div>
</div>
<?php
}
function apt_college_save($post_id)
{
$is_autosave = wp_is_post_autosave($post_id);
$is_revision = wp_is_post_revision($post_id);
if(isset($_REQUEST['wp_college_nonce']) && wp_verify_nonce($_REQUEST['wp_college_nonce'],basename(__FILE__)))
{
$is_valid_nonce = true;
}
else
{
$is_valid_nonce = false;
}
if($is_autosave || $is_revision || !$is_valid_nonce)
{
return;
}
if(isset($_REQUEST['issue_check']))
{
update_post_meta($post_id,'issue_check',sanitize_text_field(['issue_check']));
}
if(isset($_REQUEST['college-details']))
{
update_post_meta($post_id,'college-details',sanitize_text_field(['college-details']));
}
if(isset($_REQUEST['application_date']))
{
update_post_meta($post_id,'application_date',sanitize_text_field(['application_date']));
}
}
add_action('save_post','apt_college_save');
?>
There is an error with your code block.you missed out $_REQUEST['issue_check']
update_post_meta($post_id,'issue_check',sanitize_text_field(['issue_check']));
Corrected Code
update_post_meta($post_id,'issue_check',sanitize_text_field($_REQUEST['issue_check']));

prohibit adding existing value in a multidimensional array

I have a table ingredient w/c consist of(ingredient_id,name). I can perfectly add an ingredient. But i want to add a condition that prohibit on adding existing ingredient. I have the code for that condition but i think it's wrong because the condition didn't work and i can still add an existing ingredient. please help me
HERE'S MY CODE:
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value) {
$saveData[] = array('ingredient_id' => null,
'name' => trim($value)
);
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
redirect('dashboard/add_ingredients');
} }
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
if($query->num_rows > 0) {
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
} else {
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
}
return $insert_id;
}
Change your model to
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('name', $value->name);
if($query->num_rows > 0) {
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
} else {
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
}
return $insert_id;
}
That should do it. Just changing the $query line.
If that doesn't work, do a var_dump on $value just above that line, so you can see if you need to adjust the value you're targeting.
Use below code.
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value) {
$result = this->products_model->saveIngredients(trim($value));
if($result['status'])
{
$ids[]=$result['id'];
}else{
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
}
}
redirect('dashboard/add_ingredients');
} }
MODEL:
public function saveIngredients($data)
{
$query=$this->db->where('name', $data);
if($query->num_rows > 0) {
return ['status'=>FALSE];
} else {
$this->db->insert('ingredient', array('name'=>$data));
$insert_id = $this->db->insert_id();
return ['status'=>TRUE,'id'=>$insert_id];
}
}

Categories