I'm stacked on this matter. I have a model that retrieves data from a mysql database
class load_model extends CI_Model{
function __construct(){
parent::__construct();
}
Function loadsuppliers()
{
$this->db->select('SupplierID, Name');
$records=$this->db->get('supplier');
$data=array();
foreach ($records->result() as $row)
{
$data[$row->SupplierID] = $row->Name;
}
return ($data);
}
}
?>
This model submits value to a function in my controller
public function getSupplier()
{
$this->load->model('load_model');
$data['unit'] = $this->load_model->loadsuppliers();
$this->load->view('SupplierMGT', $data);
}
and I want to display the retrieved data to my view as a combo box. I tried to check if I am able to retrieve database values using echo json_encode($data) and it returns {"unit":{"2":"test","3":"Delta"}} ,
Could you help me with this? I tried using
<?php foreach($unit as $result):
print_r($result);
endforeach;?>
to check if i am able to pass the value but i failed.
Small changes in the model:
function loadsuppliers()
{
$this->db->select('SupplierID, Name');
$records=$this->db->get('supplier');
$data=array();
if($records->num_rows() > 0){
$data = $records->result_array();
}
return ($data);
}
In your view SupplierMGT.php write this:
<select name="" id="" multiple="">
<?php
if(isset($unit) && is_array($unit) && count($unit) > 0){
foreach($unit as $key=>$each){
?>
<option value="<?=$each['SupplierID']?>"><?=$each['Name']?></option>
<?php
}
}
?>
</select>
Related
I have a controller it take multiple model function results and pass it to controller I did it like this
adpreview_ctrl.php
public function showBusinessReviews($vehicleid){
$data=array();
$data['details']=$this->ads_model->getBusinessReviews($vehicleid);
$data['noOfReviews']=$this->ads_model->countReviews($vehicleid);
$this->load->view('pages/templates/header');
$this->load->view('pages/viewReviews',$data);
$this->load->view('pages/templates/footer');
}
public function countBusinessReviews($vehicleid){
$data['details']=$this->ads_model->countReviews($vehicleid);
$this->load->view('pages/templates/header');
$this->load->view('pages/viewReviews',$data);
$this->load->view('pages/templates/footer');
}
}
viewReviews.php
<?php
foreach($noOfReviews as $reviewAmount){
echo $reviewAmount.'Reviews';
}
foreach($details as $review){
$Breview=$review->rating;
if($details==null)
{?>
<?php echo '<center><b><h3>No any reviews has been posted yet!</h3></b></center>';?>
<input type="submit" name="ok" class="btn btn-primary btn-lg" value="ok">
<?php }
else{
?>
Ads_model.php
public function getBusinessReviews($Vehicleid){
$status="Approved";
$this->db->select("*");
$query=$this->db->where('Vehicleid',$Vehicleid);
$query=$this->db->where('Status',$status);
$query=$this->db->get('businessreviews');
return $query->result();
}
public function countReviews($Vehicleid){
$status="Approved";
$this->db->select("*");
$query=$this->db->where('Vehicleid',$Vehicleid);
$query=$this->db->where('Status',$status);
$query=$this->db->get('businessreviews');
return $query->num_rows();
}
what I need to know is, it gives error saying it cannot identify $noOfReviews.
foreach($noOfReviews as $reviewAmount){
echo $reviewAmount.'Reviews';
}
I need to know how to retrieve multiple model function data in view,
and $noOfReviews only gives the no of reviews, a user has given. So their, without using a foreach loop how can i get the value of that, using a foreach loop is not necessary here.
Try this:
model:
public function countReviews($Vehicleid) {
$status = "Approved";
$this->db->select("*");
$query = $this->db->where('Vehicleid', $Vehicleid);
$query = $this->db->where('Status', $status);
// it will return with only the number of data
return $query->count_all_results('businessreviews');
}
viewReviews.php
<?php
// show number of reviews
echo $noOfReviews . 'Reviews';
// show details if exists
if(!empty($details)) {
foreach($details as $review) {
// echo what you want
}
} else {
echo 'No details.';
}
?>
I'm not good in codeigniter i'm still learning this. So i need your help guys.
I want to get the data from the database that the id is equal to the value of the dropdown list button.so heres is my code.
This is my controller: controller.php
function getdataload(){
$this->load->view('data',$data);
}
I really don't know what to put in the controller.
This is my view: view.php
<html>
<body>
<label for="member">Member</label>
<select class="form-control" id="member" name="member" required onchange="showCustomer(this.value)">
<option selected="" value="">--select--</option>
<?php foreach ($members as $row): ?>
<option value="<?php echo $row->mem_id; ?>"><?php echo ucwords($row->mem_fname.' '.$row->mem_lname) ?></option>
<?php endforeach ?>
</select>
</body>
</html>
<script>
$('#member').on('change',function(){
$.post('<?php echo base_url("transactions/getdataload")?>',
{
mem_id:$(this).val()
}).done(function(res)
{
$('#select_member').text(res);
});
});
</script>
This is the other view that the called from the controller data.php
<?php
$q = intval($_GET['member']);
$con = mysqli_connect('localhost','root','','global89_point');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"global89_point");
$sql="SELECT * FROM loading_service WHERE member='".$q."'";
$result = mysqli_query($con,$sql);
echo "<table>";
echo "<tr>";
echo " <th>";
echo "Member ID";
echo "</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['member'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
please help me with this guys.
You should call database lib from controller if you do not use models and database logic write to controller see this:
public function result()
{
$this->load->library('database')
$data = array();
$service_list = $this->db->query("SELECT * FROM loading_service WHERE member='".$q."'")->result_array();
$data['service'] = $service_list;
$this->load->view('result', $data);
}
Here result view you get $service array and you can easily iterate this.
Our model in CodeIgniter will be placed in application/models/form_model.php
<?php
class Form_model extends Model {
function Formmodel() {
// load the parent constructor
parent::Model();
}
function submit_posted_data() {
// db is initialized in the controller, to interact with the database.
$this->db->insert('loading_service ',$_POST);
}
function get_all_data() {
// again, we use the db to get the data from table ‘form’
$data['result']=$this->db->get('loading_service');
return $data['result'];
}
}
?>
controller
ss Form extends Controller {
function Form(){
// load Controller constructor
parent::Controller();
// load the model we will be using
$this->load->model('form_model');
// load the database and connect to MySQL
$this->load->database();
// load the needed helpers
$this->load->helper(array('loading_service','url'));
}
//Display the posted entries
function index() {
$data['member']='Form Data';
//use the model to get all entries
$data['result'] = $this->form_model->get_all_data();
// load 'forms_view' view
$this->load->view('forms_view',$data);
}
//Process the posted loading_service
function submit() {
//use the model to submit the posted data
$this->form_model->submit_posted_data();
redirect('loading_service');
}
}
?>
you can refer this code..It will helpful for u...
I'm having difficulty with display data from the db to dropdown.
This is what I have tried:
form_model.php
function getEmployee()
{
$this->db->select('username');
$query = $this->db->get('tbl_usrs');
return $query->result();
}
form_controller.php
public function evaluate()
{
$data['employee'] = $this->form_model->getEmployee();
$this->load->view('evaluate_view');
}
evaluate_view.php
<select class="form-control">
<?php
foreach($employee as $row)
{
echo '<option value="'.$row->username.'">'.$row->username.'</option>';
}
?>
</select>
It's giving me an error saying I have an unidentified variable employee in my view file. I've seen problems relating to this but so far all their solutions didn't work for me.
When you load the view you have to send the data like this:
$this->load->view('evaluate_view', $data);
I have difficulty with populating dropdown
This is the add.php view
<?php
echo form_open('',$attributes);?>
<table cellpadding="0" cellspacing="0" class="user_table biz_table">
<tr>
<th>City:</th>
<td>
<select id="city_id" name="city_id">
<?php foreach($cities as $c){ ?>
<option value="<?php echo $c->id; ?>" <?php if ($biz['city_id']===$c->id){
>selected="selected"<?php }?> ><?php echo $c->name?></option>
<?php }?>
</select>
<tr>
<th>Neighborhood:</th>
<td>
<select id="district_id" name="district_id">
<option value=""></option>
<?php foreach($districts as $d){ ?>
<option value="<?php echo $d->id; ?>" <?php if($biz['district_id']===$d->id){?
>selected<?php }?>><?php echo $d->name?></option>
<?php }?>
</select>
<span style="color: red;"><?php echo form_error('district_id'); ?></span>
</td>
</tr>
This is the javasript. I believe it was used to refresh the page!!!!!
<script type="text/javascript">
var cities = [];
<?php foreach($cities as $city):?>
cities[<?php echo $city->id ?>] = '<?php echo $city->name?>';
<?php endforeach;?>
$(function(){
$('#city_id').change(function(){
city_id=$('#city_id').val();
Utils.loadAction('#district_id','/biz/get_children/'+city_id+'/city');
});
$('#catid_1').change(function(){
catid_1=parseInt($('#catid_1').val());
Utils.loadAction('#subcat','/biz/get_children/'+catid_1+'/category');
});
<?php if(isset($biz['rating']) && $biz['rating']>0):?>
var biz_rating=parseInt('<?php $biz['rating']?>');
if(biz_rating>0)
{
$('#rating').val(biz_rating);
$('.star-'+biz_rating).addClass('active-star');
$(".rating-hint").html($(".star-"+biz_rating).attr("title"));
}
<?php endif;?>
});
This is a controller biz.php
Class Biz extends CI_controller
{
function __construct()
{
parent::__construct();
}
public function add()
{
if(!$this->tank_auth->is_logged_in())
{
redirect('/ucp/login/');
}
$this->load->helper('form');
$biz=$this->get_form_data();
$with_review=1;
if(!empty($_POST)&&!isset($_POST['with_review']))
{
$with_review=0;
}
//validating
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('','');
$this->form_validation->set_rules('city_id', 'City',
'trim|required|intval|max_length[20]|callback_city_check');
$this->form_validation->set_rules('district_id', 'District',
'trim|intval|max_length[20]|callback_city_check');
if($this->form_validation->run())
{
//get validated data
$biz=$this->get_form_data();
}
//save business
$this->load->model('bizs');
$bizid = $this->bizs->add($biz);
redirect('/biz/'.$bizid);
}
//get cities
$this->load->model('catsAndCities','cc');
$this->cc->set_table_name('city');
$data['cities'] = $this->cc->get_top();
if(!$biz['city_id'])
{
//$city=$data['cities'][0];
$biz['city_id'] = 0;
if($this->tank_auth->get_user_city())
$biz['city_id']=$this->tank_auth->get_user_city()->id;
}
$data['districts']=$this->cc->get_children($biz['city_id']);
//$data['districts']=$this->cc->get_children($biz['city_id']);
//$data['districts']=$this->cc->get_children();
$data['biz']=$biz;
$data['heading']="Add A Business";
$this->load->view('biz/add',$data);
}
get_form_data() inside controller biz.php
private function get_form_data()
{
$biz=array(
'city_id'=>$this->input->post("city_id"),
'district_id'=>$this->input->post("district_id")
);
return $biz;
}
get User city in libraries/tank_auth.php
function get_user_city()
{
$this->ci->load->model('catsAndCities','cc');
$this->ci->cc->set_table_name('city');
$this->ci->load->helper('cookie');
if($cookie_v = get_cookie($this->ci->config-
>item('default_city_cookie_name'),TRUE))
{
if($city = $this->ci->cc->get($cookie_v,'slug'))
{
if($city->parent_id == 0)
{
$this->city = $city;
return $city;
}
}
}
$city = array_shift($this->ci->cc->get_top());
$this->city = $city;
return $city;
}
These two are in model catsandcities.php
public function get_all()
{
$data=array();
$this->db->order_by('parent_id','asc');
$this->db->order_by('`order`','asc');
$query=$this->db->get($this->table_name);
foreach($query->result() as $row)
{
$data[$row->id]=$row;
}
return $data;
}
public function get_children($parent_id)
{
$children=array();
if($items=$this->get_all())
{
foreach($items as $i)
{
if($i->parent_id === $parent_id)
{
$children[]=$i;
}
}
}
return $children;
}
the files are located here https://github.com/leungxd/upble
Thanks
I don't fully understand your question but looking at the code I see a lot of hassle to do a simple task. My advice:
Use the form helper to generate the dropdowns
Simplify the way you access your data and delegate the controller to only retrieve such data
Put as little as you can in the views, don't do any logic there
1 - use the form helper
<?= form_dropdown('city_id', $cities, 'default') ?>
This will generate the select and options html code for you. Just make sure it is inside the form_open() function.
2 - Simplify the way to access data...
Take for example your method:
public function get_children($parent_id)
{
$children=array();
if($items=$this->get_all())
{
foreach($items as $i)
{
if($i->parent_id === $parent_id)
{
$children[]=$i;
}
}
}
return $children;
}
Instead of loading all the records from your table, filter by the parent on a query level:
public function get_children($parent_id)
{
$this->db->where('id_parent', $parent_id);
$query = $this->db->get($this->table_name);
$result = $query->result();
return $result;
}
3 - Don't put logic on the views
I would suggest to create a method in your controller where you return a json encoded object and then call it by an ajax request with jquery and then populate the children dropdown:
public function get_children($parent_id)
{
$this->db->where('id_parent', $parent_id);
$query = $this->db->get($this->table_name);
$result = $query->result();
if(empty($result) == FALSE) {
return json_encode($result);
}
return NULL;
}
So whenever you call yoururl/controller/get_children and pass the parent id by a post you'll get the children for that city in a json encoded way that you can get with jquery to manipulate data client-side, instead of having thousands of records bloating up your html.
Read the guidelines of stackoverflow or you won't get much help, and try to be clear on what problem you are trying to solve. Good luck!
I just added a subdomain, and it solved the problem.
thanks
I Need help on how can i get values of second select box based on first select box
This is view:
$(document).ready(function() {
$('#state').change(function() {
// Get an instance of the select, and it's value.
var state = $(this),
stateID = state.val();
// Add if statement to check if the new state id
// is different to the last to prevent loading the same
// data again.
// Do the Ajax request.
$.ajax({
url : 'http://localhost/ci_ajax/select/get_cities/'+stateID, // Where to.
dataType : 'json', // Return type.
success : function(data) { // Success :)
// Ensure we have data first.
if(data && data.Cities) {
// Remove all existing options first.
state.find('option').remove();
// Loop through each city in the returned array.
for(var i = 0; i <= data.Cities.length; i++) {
// Add the city option.
state.append($('option').attr({
value : data.Cities[i].value
}).text(data.Cities[i].city));
}
}
},
error : function() {
// Do something when an error happens?
}
});
});
});
<form action="" method="post">
<select name="state" id="state">
<option>Select</option>
<?php foreach($states as $row):?>
<option value="<?php echo $row->id?>"><?php echo $row->states;?></option>
<?php endforeach;?>
</select>
<select id="cities" name="cities">
<option>Select</option>
</select>
This is controller:
class Select extends CI_Controller{
function index(){
$data['states']=$this->load_state();
$this->load->view('form',$data);
}
function load_state(){
$this->load->model('data_model');
$data['states']=$this->data_model->getall_states();
return $data['states'];
}
function get_cities() {
// Load your model.
$this->load->model('data_model');
// Get the data.
$cities = $this->data_model->get_cities();
// Specify that we're returning JSON.
header('content-type: application/json');
// Return a JSON string with the cities in.
return json_encode(array('Cities' => $cities));
}
}
This is model:
class Data_model extends CI_Model{
function getall_states(){
$query=$this->db->get('states');
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
function get_cities(){
$this->db->select('id,cities');
$this->db->from('cities');
$this->db->where('s_id',$this->uri->segment(3));
$query=$this->db->get();
if($query->num_rows()>0){
foreach($query->result() as $row){
$data[]=$row;
}
return $data;
}
}
}
Please help on this hopefully provide the correct code.
Because you are accessing the get_cities() function directly, rather than from another function in the controller, your return statement will not actually print the json array to the page.
return json_encode(array('Cities' => $cities));
There are 3 ways to print it: the first is to print or echo the json array (bad practice), the second is to use a view that prints the raw text sent to it. I.E.
$this->load->view('raw', array('data' => json_encode(array('Cities' => $cities)));
With raw.php being just:
<?php print $data; ?>
Or finally you can use the set_output() function in the output class like this:
$this->output->set_output(array('data' => json_encode(array('Cities' => $cities)));
You may also want to make your function load_state() private if it is only going to be accessed from the index() function.
You may have other problems with your code but that is the most obvious one.