unable to show the selected text data in codeigniter php - php

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 }?>

Related

Codeigniter - avoiding duplicate entries for database

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

Trying to make a search bar with a MINI PHP MVC

I am trying to make a search bar for my application.
I am using the following Mini Framework: https://github.com/panique/mini
What I want to do is have an input field where you type an username, and then a table is displayed underneath with all the information from the Database.
Environment:
PHP 7.4
Apache
CentOS 8
SQL Server 2019
My problem is, I don't know how to pass the input value to the controller and then to the model.
Let me show you what I have tried:
Account Model:
public function getUser($name)
{
$sql = "SELECT * FROM dbo.user_table WHERE Name = :name ORDER BY UserID DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':name' => $name));
return $query->fetchAll();
}
Account Controller:
/**
* ACTION: getUser
*/
public function getUser()
{
if(isset($_POST['search_user'])) {
$checkUser = $this->model->getUser($_POST['username']);
}
}
My View:
<form action="<?php echo URL; ?>account/getUser" method="POST" class="mb20">
<div class="row">
<div class="input-wrap col-sm-12">
<input type="text" placeholder="Type username" name="username" autocomplete="off" />
</div>
</div></br>
<input type="submit" value="Search" name="search_user" />
</form>
I am not sure how to echo the result in the view. Maybe someone here could guide me in the correct direction.
Thanks!
Account Controller:
/**
* ACTION: getUser
*/
public function search()
{
if(isset($_POST['search_user'])) {
$checkUser = $this->model->getUser($_POST['username']);
}
require APP . 'view/search/index.php'; // your search view path
}
Search View:
<form action="<?php echo URL; ?>search" method="POST" class="mb20">
<div class="row">
<div class="input-wrap col-sm-12">
<input type="text" placeholder="Type username" name="username" autocomplete="off" />
</div>
</div></br>
<input type="submit" value="Search" name="search_user" />
</form>
<?php
if (isset($checkUser)) {
echo '<ul>';
foreach ($checkUser as $key => $value) {
echo '<li>';
echo $value->name;
echo '</li>';
}
echo '</ul>';
}
In this way, if there's the $_POST['search_user'], the function search will perform the search and put the result on the $checkUser variable. The variable will be still present on the View because you're requiring it after the $checkUser declaration. Then, the View checks if the variable is present and displays the results.
IMPORTANT
The line echo $value->name; is a dangerous behavior, because it can allow XSS, so, before rendering anything from the database, remember to escape it properly. Some ways to do it:
How to prevent XSS with HTML/PHP?
https://www.php.net/manual/pt_BR/function.strip-tags.php

How do I get the data from a view to another view in ionic?

I have followed this tutorial ionic/angular - get data from database - data loaded, but no output on site
on how to retrieve data from database and show it in ionic but the problem is the data can only be seen in one view and I dont know how to view it in another view
screencap - I have successfully display the recipes in my ionic from my database and when I click the pen icon it should be displaying the recipe name, ingredients and more
screencap 2 - but when I click it it doesnt show any data.
here's my code for viewing data :
user_model.php (codeigniter - model )
public function user_recipe_data()
{
$this->db->select('*');
$this->db->from('usersrecipes');
$this->db->join('user', 'user.user_id = usersrecipes.user_id');
$this->db->where('usersrecipes.user_id = 12 ');
$query = $this->db->get();
return $query->result_array();
}
Main.php ( codeigniter - controller )
public function get_user_recipe_data()
{
$postdata = json_decode(file_get_contents("php://input"));
$user_recipe = $this->User_model->user_recipe_data();
echo json_encode($user_recipe);
}
RecipeService.js (ionic)
.factory('getRecipeService', function($http){
return {
all: function() {
return $http.get("http://localhost/admin-recipick/api/Main/get_user_recipe_data");
},
get: function(Recipe_ID) {
q = $http.get("http://localhost/admin-recipick/api/Main/get_user_recipe_data");
for (var i = 0; i < q.length; i++) {
if (q[i].id === parseInt(Recipe_ID)) {
return q[i];
}
}
return null;
}
};
});
controller.js (ionic)
getRecipeService.all().then(function(payload) {
$scope.userrecipedata = payload.data;
console.log(payload);
});
profile.html ( ionic )
<ion-list>
<ion-item ng-repeat="recipe in userrecipedata" class="item-remove-animate item-avatar item-icon-right" type="item-textu-wrap" href="#/app/recipes/{{recipe.Recipe_ID}}">
<img ng-src="img/food/porkmenudo.jpg">
<h2>{{recipe.Recipename}}</h2>
<p>{{recipe.Ingredients}}</p>
<i class="icon ion-edit"></i>
<ion-option-button class="button-assertive" ng-click="remove(recipe)">
Delete
</ion-option-button>
</ion-item>
</ion-list>
recipe-detail.html ( ionic - in this html I want to display the data here also but it shows no data in the input type. What should I do?)
<div class="list">
<label class="item item-input">
<span class="input-label">Index Name</span>
<input type="text" ng-model="recipe.Recipe_ID">
</label>
<label class="item item-input">
<span class="input-label">Recipe Name</span>
<input type="text" ng-model="recipe.Recipename">
</label>
<label class="item item-input">
<span class="input-label">Ingredients</span>
<input type="text" ng-model="recipe.Ingredients">
</label>
<label class="item item-input item-select">
<span class="input-label">Cooking Time</span>
<select ng-model="recipe.Cookingtime">
<option value="20mins">20mins</option>
<option value="30mins">30mins</option>
<option value="1hr">1hr</option>
</select>
</label>
<label class="item item-input">
<textarea placeholder="PROCEDURE" rows="12" ng-model="recipe.Procedure">
</textarea>
</label>
<button class="button button-block button-assertive h1" ng-click="AddRecipe()">Update Recipe</button>
</div>
Use http for controller
.controller('Ctrl', function($scope, $http, $stateParams) {
$scope.userrecipedata = [];
$http.get('http://localhost/admin-recipick/api/Main/get_user_recipe_data').success(function(response){
$scope.userrecipedata = response;
});
})

Codeigniter - Dependent Select Box with database

i'm just wanna ask again about codeigniter.
I want to make dependent select form in codeigniter with sql server database.
I have an database table name MS_UPB (it contains a location) and MS_RUANG (it contains a room in that location). My task is to show the room where the MS_RUANG.kd_lokasi (this is the room location ID) = MS_UP.kd_lokasi (this is the location ID) and show it in the dependent select box codeigniter
My Views:
<?php
echo form_open('admin/laporan/tampildbr',$att)
?>
<div class="control-group">
<label class="control-label" for="inputEmail">Unit Kerja</label>
<div class="controls">
<select name="unit" id="unit">
<?php
foreach ($isdata as $row) {
echo "<option value='".$row->KDUPB."|".$row->NAMAUPB."'>".$row->NAMAUPB."</option>";
}
?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Ruangan</label>
<div class="controls">
<select name="ruangan" id="ruangan" id="ruangan_label">
<option value=""></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Jenis</label>
<div class="controls">
<input type="radio" name="jenis" value="DAFTAR BARANG RUANGAN" />Daftar Barang ruangan
</div>
<div class="controls">
<input type="radio" name="jenis" value="REKAP DBR" />Rekap DBR
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn btn-success" name="submit" formtarget="_blank">Kirim</button>
</div>
</div>
</form>
<p> </p>
<p> </p>
<?php form_close();?>
<script type="text/javascript">
$('#ruangan,#ruangan_label').hide();
$('#unit').change(function(){
var unit_id = $('#unit').val();
if (unit_id != ""){
var post_url = "admin/laporan/getruangan" + unit_id;
$.ajax({
type: "POST",
url: post_url,
success: function(ruangan) //what's this ruangan mean?
{
$('#ruangan').empty();
$('#ruangan, #ruangan_label').show();
$.each(ruangan,function(kd_ruang,ruang)
{
var opt = $('<option />');
opt.val(kd_ruang);
opt.text(ruang);
$('#ruangan').append(opt);
});
} //end success
}); //end AJAX
} else {
$('#ruangan').empty();
$('#ruangan, #ruangan_label').hide();
}
});
</script>
My Controller:
function getruangan($unit)
{
$unit=explode('|',$unit);
$unitkerja=$unit[0];
$this->load->model('admin/laporanmodel','',TRUE);
header('Content-Type: application/x-json; charset=utf-8');
echo (json_encode($this->laporanmodel->get_ruangan($unitkerja)));
}
My Model:
function get_ruangan($unit)
{
$this->db->select('kd_ruang,namaruang');
$this->db->from('MS_RUANG');
$this->db->where('kd_lokasi, "'.$unit.'"');
$query=$this->db->get();
$ruangan=array();
if($query->result()){
foreach ($query->result() as $ruang) {
$ruangan[$ruang->kd_ruang] = $ruang->kd_ruang;
}
return $ruangan;
} else {
return FALSE;
}
}
please help me, thanks for your help :)
I think you have issue while appending the value to your select box.
I would tell you to do all required stuff in model itself. If you do so, we can reduce execution time of one for loop
Try changing in your model like this.
In Model
if($query->result()){
$option = "<option>Select the value</option>";// this is for default value.
foreach ($query->result() as $ruang) {
$ruangan[$ruang->kd_ruang] = $ruang->kd_ruang;
$option .= "<option value='$ruang->kd_ruang'>{$ruang->kd_ruang}</option>".
}
return $option;
} else {
return FALSE;
}
In model only we are generating required html for our view.
In Controller
//header('Content-Type: application/x-json; charset=utf-8');// comment this line
echo ($this->laporanmodel->get_ruangan($unitkerja));
I have removed json part in controller. We will take plain text here.
In view
Im changing entire success() in ajax,
success: function(ruangan) //what's this ruangan mean?
{
$('#ruangan').append(ruangan);// just append the value coming from ajax call here.
}
We have reduced execution time of one loop.
Hope it helps.

CodeIgniter: Populate an input text in the view from data array grabbed from database

This return of print_r($query->result()); would be:
Array ( [0] => stdClass Object ( [guest_name] => Test Name [guest_gender] => Male [guest_nic_pp_dl] => 123456789 ) )
What I need is to pass those values into input text boxes, radio buttons and dropdowns in the view respectilvely.
For example, I need 'guest_name' to be in an input, 'guest_gender' value to be selected on the view, and dropdown value corresponding to 'guest_nic_pp_dl' to be selected on a dropdown (HTML select).
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$this->banquet_model->talk_to_new_guest_table($guest_name);
$this->load->view('/main/banquet_view');
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo set_value('guest_name'); ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>
make some changes in
Controller :
$guest=$this->banquet_model->talk_to_new_guest_table($guest_name);
//creating data array from returned result
$data['guest_name']=$guest->guest_name;
$data['guest_gender']=$guest->guest_gender;
$data['guest_nic_pp_dl']=$guest->guest_nic_pp_dl;
//loading view with data
$this->load->view('/main/banquet_view',$data);
more important all these data array element will be available as variable on view page like
$data['guest_gender'] as $guest_gender
The answers from Rajeev Ranjan and Prasanth are ok but on the line return $query->result(); you can do thisreturn $query->row(); the reason is because the result() returns an array of objects which needs to be iterated while the row() object returns a single object which you can reference without iterating with a loop. I hope this will help
Try something on the lines of:
Controller:
function get_customer_details() {
$guest_name = $this->input->post('guest_name');
$data = $this->banquet_model->talk_to_new_guest_table($guest_name);
if ($data != 0) {
$this->load->view('/main/banquet_view', $data);
}
}
Model:
function talk_to_new_guest_table($guest_name) {
$query = $this->db->query(" SELECT guest_name, guest_gender, guest_nic_pp_dl
FROM new_guest
WHERE guest_name LIKE '$guest_name%'
LIMIT 1 ");
if($query->num_rows()>0) {
return $query->result();
}
else {
return 0;
}
}
View:
<div class="control-group">
<label for="guest_name" class="control-label"><i class="icon-user"></i> Name: </label>
<div class="controls">
<div class="input-append">
<input type="text" id="appendedInputButtons" class="span2" name="guest_name" value="<?php echo $guest_name; ?>">
<input class="btn" type="submit" name="searchGuest" value="Search">
</div>
<?php echo form_error('guest_name'); ?>
</div>

Categories