CodeIgniter Getting the result of a query as a text input value - php

I wrote a small piece to get a value from a database table according to the input user provides. Quickly here are the events:
User inputs number to an input and submit form
That data are supposed to call the controller, and then the controller have to match and grab relevant data from the database table, and pass it to the controller again.
Then the controller must pass it to the view, where another text input (readonly) picks up the data as the value.
But what I received was an error:
Message: Undefined variable: due_amount
Filename: main/new_payment.php
Line Number: 148
Line number 148 in new_payment.php is
);
in the View.
This is my Model:
function get_by_room_number($room_data) {
$this->db->select('due_amount');
$query = $this->db->get_where('rooms', array('room_number' => $room_data), 1);
if($query->num_rows()>0) {
foreach ($query->result() as $row) {
return $row->due_amount;
}
}
This is the Controller:
function search_by_number() {
$room_data = $this->input->post('room_number');
$due_amount = $this->payments_model->get_by_room_number($room_data);
$this->index();
}
This is the View: (new_payment.php)
<?php echo form_open('payments/search_by_number'); ?>
<?php $data = array(
'name' => 'total_amount',
'id' => 'appendedPrependedInput',
'class' => 'span2',
'value' => $due_amount
); // Line Number 148
echo form_input($data);
?>
<?php echo form_close(); ?>

Try like
$data['due_amount'] = $this->payments_model->get_by_room_number($room_data);
and try to sent it to view like
$this->load->view('view_file',$data);
and at your view file echo it like
echo $due_amount;
assuming that $data is the array that you are passing to your view from your controller function.You cont pass a variable from controller to view.You need to pass it through an array data and then you can get the variable with that variable name

You should assign due_amount to $data variable and pass it to view. Like this:
$data['room_data'] = $this->input->post('room_number');
$data['due_amount'] = $this->payments_model->get_by_room_number($data['room_data']);
$this->load->view('my_view', $data);
Then in view you could do:
print_r($room_data);
print_r($due_amount);
CodeIgniter User Guide might help you understand it better.

Related

Codeigniter - input data save in multiple arrays and db table

I've an existing form which is passing the input data to the model in an array format. $postdata has all the data from the view and sending to model.
Controller:
$inquiry_id = $this->input->post('inquiry_id');
$postdata = $this->input->post();
$this->load->model('Design_model');
$this->Design_model->insertdata($postdata,$inquiry_id);
Model:
function insertdata($data = array(), $inquiry_id){
$sql = $this->db->query("select * from design where inquiry_id='".$inquiry_id."'");
if($sql->num_rows() == 0){
$sql_query = $this->db->insert('design', $data);
}
else{
$this->db->where('inquiry_id', $inquiry_id);
$this->db->update('design', $data);
}
}
Above is working fine. Now, I'd like to add few fields in the view and save in a different database table. Need to exclude the new field values from $postdata array getting saved. Need to find the best approach to do this. I can start with some name for all the new fields, so that we can add any filter if available to exclude from the $postdata.
You can use elements() function from Array helper.
$array = array(
'id' => 101,
'title' => 'example',
'desc' => 'something',
'unwanted' => 'bla bla'
);
$filtered_array = elements(array('id','title','desc'),$array); //you can use this directly to the post data
$this->Design_model->insertdata($filtered_array,$inquiry_id);
You can use array_merge() or array_push() functions to add new fields to the array.
Let's say you have following data
$postdata = array("name"=>"xyz",
"email"=>"xyz#gmail.com",
"age"=>"40",
"gender"=>"Male",
"occupation"=>"Engineer"
);
Of which first 3 records are from old fields and last 2 are from new fields as you saying.
You need to find last index of first set i.e. '3' Now you can do this.
$firstDb = array_splice($postdata,0,3); //here 3 is index we are using to get first 3 records from $postdata
$secondDb = array_slice($postdata,0,3); //here 3 is index we are using to get records from position 3 from $postdata
Output:
$firstDb = array("name"=>"xyz","email"=>"xyz#gmail.com","age"=>"40");
$secondDb = array("gender"=>"Male","occupation"=>"Engineer");
Now you can insert you records as you wish to. Happy coding

How to solve Message: Trying to get property of non-object error in Codeigniter?

I'm very fresher in CodeIgniter and practicing. I'm now developing a simple Codeigniter application just for practicing. I've Banks and its branches in the database. I just want to show branches with its bank name. Branches are showing but in the controller while getting banks, this error is showing. I tried these in SO links, but nothing found works.
"A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object"
in Line Number: 85 and 91
This is my controller
function ShowBranchList() {
$branch_list = $this->FD_Model->get_all_branches();
$get_bank = $this->FD_Model->get_bank_by_branch($branch_list->bankid); //This is Line Number 85
if($branch_list ){
$data = array(
'pagetitle' => 'Branch List View',
'branch_list_data' => $branch_list,
'br_bank' => $get_bank['bank_name'],//This is Line Number 93
);
}
Model
/*function for getting all branches*/
function get_all_branches() {
$this->db->order_by( $this->brid, $this->order );
return $this->db->get( $this->brtable )->result();
}
/*function for getting banks by branches*/
function get_bank_by_branch( $id ) {
$this->db->where( $this->bid, $id);
return $this->db->get( $this->banktable )->row();
}
And finally, this is my View
foreach ($branch_list_data as $branch_list)
{
<?php echo $branch_list->brname ?>
<?php echo $br_bank; ?>
}
Anyone know the issue?
Update
When I'm tring to view the query
echo $this->db->last_query();
Result
SELECT * FROM tbl_bankmaster WHERE bid IS NULL
The value $branch_list->bankid is null.When I'm hardcoding some values the view page is showing without any error.
do like this
$get_bank = $this->FD_Model->get_bank_by_branch($branch_list[0]->bankid);
AND
'br_bank' => $get_bank[0]->bank_name # this will work maybe
or
'br_bank' => $get_bank[0]['bank_name']
Its 0 indexed array so you need to add the key to access the child's
Change your data in view like this
foreach ($branch_list_data as $branch_list)
{
echo $branch_list['brname']; //change your data like this
echo $br_bank;
}
I finally make it happen with the help of Abdulla Nilam's answer. I just passed the value in array like
'br_bank' => $get_bank->bank_name
Now the view is working.
get_bank_by_branch($branch_list->bankid); This method returning only object.
$get_bank this variable you're accessing by an array, but it's an object.

Problems Trying Insert Data in Database using $this->input->post() - Codeigniter

Im trying use "$this->input->post();" of Codeigniter to do not need specify each field in my form. But im getting troubles when try insert into Database.
Look my controller:
public function cadastrar(){
$var = $this->input->post(null, TRUE);
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
My controller is simplified here because i know how to handle database in codeigniter.
The result of this post was:
Array ( [nome] => Raphael [sobrenome] => Schubert [cpf] => 893.528.432-89 [rg] => 4529875231908472 [telefone] => (53) 2980-5792 [celular] => (53) 9 2180-7529 [rua] => Israel de Almeida [numero] => 859 [cep] => 88.312-000 [bairro] => São Vicente [cidade] => ITAJAÍ [estado] => Santa Catarina [email] => rfswdp#gmail.com [tipo] => pf [cnpj] => 34.827.481/2834-78 [inscricaoestadual] => 34120489032814930128 [razaosocial] => Teste [nomefantasia] => Disney [dataaberturaempresa] => 10/21/15 [proprietario] => Marcos Aurelio )
I normaly use this way to insert:
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
And works...
But i was trying to use just $this->input->post(); to get all fields from form. Because my actualy application will have hundreds of fields and i was trying to do not write each line.
So my model actually was:
public function inserir($var){
if($var!=NULL):
print_r($var);
$this->db->insert('tb_usuarios',$var);
endif;
}
But i`m getting and error saying:
Message: Undefined property: Clientes::$db
and
Message: Call to a member function insert() on null
My table name is: "tb_usuarios"
I changed all fields in database to accept NULL to see if i`m get some field name wrong... but not work...
Any tips??
There is no need to catch the POST var inside $var. You can see POST variable inside the model very well. So all you need to do in the controller is:
public function cadastrar(){
$this->load->model('m_clientes');
$this->m_clientes->inserir();
}
,and inside your model:
public function inserir(){
if( count($this->input->post()) > 0):
$this->db->insert('tb_usuarios',$this->input->post());
endif;
}
The fields names in your form must correspond to the column names inside your table.
The message Message: Call to a member function insert() on null means you forgot to load the database library, just like remiheens said.
But my advice is, to use form validation for your fields, so you may be sure all necessary fields are completed using the required data format for each one of them. Although this may require allot of coding, there is no other safe way from errors on database operations. You cannot trust the user to insert the data correctly, that's why you need form validation.
In here $var = $this->input->post(null, TRUE); you use null. null is not valid input name. name = ''
and this will works $this->input->post('user_name',TRUE);
cz of it has input tag name (name = 'user_name').
We use ,TRUE) next to input post field to allows XSS Protection
$var = $this->input->post(null, TRUE); Is Wrong
while you trying this, it shows
Message: Undefined property: Clientes::$db and Message: Call to a member function insert() on null.
will not work
public function cadastrar(){
$var = $this->input->post(null, TRUE);//will never give valid response
$this->load->model('m_clientes');
$this->m_clientes->inserir($var);
}
Works well
public function cadastrar(){
$this->load->model('m_clientes');
$data = array(
'user_name' => $this->input->post('user_name',TRUE);
'user_phone' => $this->input->post('user_phone',TRUE);
'user_role' => $this->input->post('user_role',TRUE);
);
$this->name_of_model->inserir($data);
$this->load->model('m_clientes');
}
This is because your database isn't loaded into codeigniter instance. ($this->db)
Just try to autoload "database" library (config/autoload.php) or load/connect your database in your model with :
$this->load->database();
Don't forget to edit your config/database.php ;)
I handle hundreds of fields everytime but I also validate basically each one. I always do this:
$customer['name'] = $this->input->post('customer_name');
$customer['age'] = $this->input->post('customer_age');
$customer['country'] = $this->input->post('customer_country');
$customer['city'] = $this->input->post('customer_city');
// validations
if(isAgeValid($customer['age']) == FALSE)
{
echo 'Hold on, your age...hmm check it out!';
return;
}
$this->customers_model->add($customer);
The function that handles the insertion only has this:
public function add($data)
{
$data = $this->security->xss_clean($data);
$this->db->insert('customers', $data);
return $this->db->insert_id();
}
Pretty clean and simple. Now, if you don't want to validate the fields or just want to validate some of them and want to insert the others without validation this is what I purpose based on the previous code:
// validations..
if(isAgeValid());
$customer = array();
foreach($_POST as $key => $value)
$customer[$key] = $value;
$this->customers_model->add($customer);
$data = array(
'user_name' => $this->input->post('user_name');
'user_phone' => $this->input->post('user_phone');
'user_role' => $this->input->post('user_role');
);
$this->load->model('name_of_model');
$this->name_of_model->inserir($data);
Model:
public function inserir($data)
{
$this->db->insert('***', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
}

CakePHP - passing multiple values from a view element to the controller

I want to pass some values to my controller from the view.
Actually I'm using the following code:
<?
echo $this->element('produtos-categoria', array(
'categoria_id' => $produtos['Produto']['categoriasproduto_id'],
'produto_id' => $produtos['Produto']['id']
));
?>
But I'm not able to get the second value in my controller, just the first value is coming:
public function list_categories($categoria_id = null, $produto_id = null ) {
pr($produto_id); exit; //empty
}
Anyone can help how to get the second value?
I donno what are you trying to achieve but to get the second variable you would need to set the second parameter to your method.
// If you want to set variable from a function and get it from an other function
public function an_other_function(){
$this->listacategorias(22, 333);
}
public function listacategorias($categoria_id = null, $produto_id = null ) {
var_dump($categoria_id);
var_dump($produto_id);
}
// If you want to set and get variable from url
host_or_domain_name/controller_name/listacategorias/22/33

I want to display the last 4 pages in Yii?

Studying Programming Yii, I want to display the last 4 pages:
SiteController.php
public function actionStart()
{
$featured = Page::model()->findAllByAttributes(
array(),
$condition = 'featured = :featureId',
$params = array(
':featureId' => 1,
)
);
$this->render('/layouts/start/start', array('featured'=>$featured));
}
/layouts/start/start.php
<?php print_r($this->featured); ?>
The latter file does not display anything, and should be an array with the data, how do I get it?
$this->render('/layouts/start/start', array('featured'=>$featured));
Here, you are sending array(association array) of values to the View. You can access these values by calling the array Key.
So, your code should be
<?php echo print_r($featured); ?>
Another example.
$this->render('myView', array('myName'=>'Hearaman','myAge'=>25));
I'm sending my name and age to View. To show my name and age, i should call the keys
echo $myName;
echo $myAge;
Eliminate the $this for featured.
<?php echo print_r($featured, true); ?>

Categories