how do i get the data from view in codeigniter - php

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...

Related

php refreshing only data in page

i'm a php nearby. I have a problem with my form. I connect the controller with db and extract a question and his three answers. If i click on one of this, the system return the second question, under the first question. If i click on one of the seconds answers, the system return the thirth question overwrite the second question.
I would like that second question (and its answers) overwrite the first (and its answers). How i can?
db structure
view
1) index.php
<?php
error_reporting(E_ERROR | E_PARSE);
require_once 'controllers/controller.php';
$controllers = new Controller();
$controllers->cercaDomanda(1);
$controllers->cercaRisposta(1);
$controllers->cercaNuovoId($id);
?>
2) Controller.php
<?php
require_once('models/Domanda.php');
require_once('models/Risposta.php');
require_once ('models/Model.php');
class Controller {
public $domanda;
public $risposta;
public $model;
public function __construct(){
$this->domande = new Domanda(); //istanziamo la classe domanda
$this->risposte = new Risposta(); //istanziamo la classe risposta
$this->model = new Model(); //istanziamo la classe risposta
}
public function cercaDomanda($id){
$reslt = $this->domande->getDomanda($id);
include 'views/basicView.php';
}
public function cercaRisposta($id){
$reslt2 = $this->risposte->getRisposta($id);
include 'views/basicView.php';
}
public function cercaNuovoId($id){
include 'views/basicView.php';
$reslt3 = $this->model->getIdNext();
$reslt4 = $this->cercaDomanda($reslt3);
$reslt5 = $this->cercaRisposta($reslt3);
}
}
?>
3)Domanda.php
<?php
require_once 'models/Domanda.php';
class Domanda {
public function getDomanda($id){
$dbconnection = pg_connect("host=***port=***dbname=***user=***password=***");
$query = 'SELECT domanda FROM public."Domande" WHERE "id"='.$id;
$result = pg_query($query);
return $result;
pg_close($dbconnection);
}
}
?>
4)Risposta.php
<?php
require_once 'models/Risposta.php';
class Risposta {
public function getRisposta($id){
$dbconnection = pg_connect("host=***port=***dbname=***user=***password=***");
$query = 'SELECT * FROM public."Risposte" WHERE "id_domanda"='.$id;
$result = pg_query($query); //or die ('Query fallita: ' .pg_last_error());
return $result;
pg_close($dbconnection);
}
}
?>
5)Model.php
<?php
require_once 'models/Model.php';
class Model {
public function getIdNext(){
if(isset($_POST['btnScelta'])){
$result = $_POST['btnScelta'];
return $result;
}
}
}
6)View
<html>
<head></head>
<body>
<form action='index.php' name='chatbotyForm' method="POST">
<table>
<?php
echo "<tr>";
$domanda = pg_fetch_array($reslt, null, PGSQL_ASSOC);
print $domanda['domanda'];
echo "</tr>";
?>
</table>
<?php
while ($rispost = pg_fetch_object($reslt2)) {
print "<td><button type='submit' name='btnScelta'
value='$rispost->id_domanda_successiva'>$rispost->risposta</button>
</td>";
}
?>
</form>
</body>
</html>
In your view:
...
<?php
while ($rispost = pg_fetch_object($reslt2)) {
print "<td><button type='submit' name='btnScelta'
value='$rispost->id_domanda_successiva'>$rispost->risposta</button>
</td>";
}
?>
you are setting only one value in each button. which is available as $_POST['btnScelta'] and that is used to render your last question.
Edit previous contents removed because they are not relevant to the question.
To render two questions pass two ids as the button value.
To remove the first question remove the two lines from your index.php
1) index.php
<?php
error_reporting(E_ERROR | E_PARSE);
require_once 'controllers/controller.php';
$controllers = new Controller();
/* remove the following two lines the first question wont be rendered.*/
//$controllers->cercaDomanda(1);
//$controllers->cercaRisposta(1);
$controllers->cercaNuovoId(/*$id*/);
?>
Now make controller process two question display.
class Controller {
public function cercaNuovoId(/*$id*/){
// include 'views/basicView.php';
$reslt3 = $this->model->getIdNext();
// render previous question only if a value exists.
if ($result3) {
list($current, $previous) = explode(',', $result3);
$this->cercaDomanda($previous);
$this->cercaRisposta($previous);
}
// show the first question on first visit.
if (empty($current)){
$current = 1;
}
$reslt4 = $this->cercaDomanda($current);
$reslt5 = $this->cercaRisposta($current);
}
}
Now in the view make modification for button to have two values seperated by comma. current question id is available as $id from Controller::cercaRisposta()
<?php
while ($rispost = pg_fetch_object($reslt2)) {
print "<td><button type='submit' name='btnScelta'
value='{$rispost->id_domanda_successiva},{id}'>$rispost->risposta</button>
</td>";
}
?>
</form>
you can also pass the previous question id by changing form's action property with a query like index.php?previous=$id.

My search code is not outputting any result on codeigniter

Please help!!
I am trying to search database to produce results for my search query but it does not output any result even when the searched term exist in the database
Here is my controller
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model("profile_model");
$this->load->model("model_home");
}
public function index(){
$data = array();
$search_term = $this->input->post('search');
if($query = $this->model_home->car_search())
{
$data['car'] = $query;
}
$this->load->view('search_results', $data);
}
}
Here is my model
public function car_search($search_term='default')
{
$this->db->select('*');
$this->db->like('car_make',$search_term);
$this->db->or_like('car_model',$search_term);
$this->db->or_like('car_year',$search_term);
$this->db->or_like('registration_number',$search_term);
$this->db->or_like('engine_number',$search_term);
$this->db->or_like('chasis_number',$search_term);
$query = $this->db->get('cars');
return $query->result_array();
}
My search form
<?php
echo form_open('search');
echo form_input(array('name'=>'search'));
echo form_submit('search_submit','submit');
?>
My search result page
<?php
if(isset($car)) :
foreach($car as $row) {
echo $row['car_make'];
} //<-- moved this line
else :
echo '<h1> Not working </h1>';
endif; ?>
Its always outputting "Not Working"
This code is a bit of a mess, if you tidy it up you will see the error
Your code without all the <?php and ?>
<?php
$count = 1;
if(isset($car)) :
foreach($car as $row) {
$count++;
}
echo $row['car_make']
else :
echo '<h1> Not working </h1>';
endif;
?>
So you should see the } in the wrong place ending the foreach loop, quite easily now, so change it to
<?php
$count = 1;
if(isset($car)) :
foreach($car as $row) {
$count++;
echo $row['car_make'];
} //<-- moved this line
else :
echo '<h1> Not working </h1>';
endif;
?>
As you are getting the Not Working message I have to assume there is a problem with your querying of the database.
Probably as you are not passing the search term into the car_search method call. So try passing the paramter you get from the POSTed data.
public function index(){
$data = array();
if($query = $this->model_home->car_search($this->input->post('search'))) {
$data['car'] = $query;
}
$this->load->view('search_results', $data);
}
You should also look at the default value used in the car_search method as the string 'default' will almost definitely cause the query to return no results.

populate dropdown in codeigniter

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

save not working properlly

controller
userdetails.php
class Controller_Userdetails extends Controller {
public function action_index() {
$view = new View('userdetails/index');
$this->response->body($view);
}
public function action_add() {//load adddetails.php
$userdetails = new Model_Userdetails();
$view = new View('userdetails/adddetails');
$view->set("userdetails", $userdetails);
$this->response->body($view);
}
public function action_post() {//save the post data
$userdetails_id = $this->request->param('id');
$userdetails = new Model_Userdetails($userdetails_id);
$userdetails->values($_POST);
$userdetails->save();
$this->request->redirect('index.php/userdetails');
}
}
views
adddetails.php
<?php echo Form::open('userdetails/post/'.$userdetails->id); ?>
<?php echo Form::label("first_name", "First Name"); ?>
<?php echo Form::input("first_name", $userdetails->first_name); ?>
<br />
<?php echo Form::label("last_name", "Last Name"); ?>
<?php echo Form::input("last_name", $userdetails->last_name); ?>
<br />
<?php echo Form::label("email", "Email"); ?>
<?php echo Form::input("email", $userdetails->email); ?>
<br />
<?php echo Form::submit("submit", "Submit"); ?>
<?php echo Form::close(); ?>
I am trying to insert the data into database.The name and email field are loading correctly,if i enter values and hit enter it is redirecting to other page but objects not saved in database.Need help to solve this.
I sometimes find problems in saving while using
$userdetails->values($_POST);
try using
$userdetails->first_name = $this->request->post('first_name');
$userdetails->last_name= $this->request->post('last_name');
$userdetails->email= $this->request->post('email');
Assuming the model is an ORM model (class Model_Userdetails extends ORM {}), you should use ORM::factory() to load the model. Furthermore it's recommended to use the expected parameter to be sure only the values you want to be inserted are used.
$user_details = ORM::factory('Userdetails');
$user_details->values($this->request->post(),
array('first_name', 'last_name', 'email')
);
$user_details->save();

Populating <select> with mysql data dynamically using CodeIgniter

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>

Categories