We help IT Professionals succeed at work.

CodeIgniter

44

Solutions

59

Contributors

CodeIgniter is an open-source software rapid development web framework used to build dynamic websites with PHP. The software is partly based on the model–view–controller (MVC) pattern, although models and views are optional. It is typically recognized for its speed when compared to other PHP frameworks.

Hi Experts


Could you point how to correctly present an array already obtained from CodeIgniter's model in the View?

Controller's code:
$this->data['fk_seguradora_f'] = $this->seguradora_model->get_seguradoras();

Open in new window


Model's Code:
function get_seguradoras( ) 
{ 
	$fk_seguradora_f = array();

	$query=$this->db->query("SELECT id_seguradora, nome_seguradora FROM system_seguradora");
	$fk_seguradora_f = $query->result_array();

	return $fk_seguradora_f;
}

Open in new window


View's code
<div class="row">
	<div class="col-xs-12 mb15">
		<div class="input-group">
			<span class="input-group-addon ">
				<i class="fa fa-search c-gray"></i>
			</span>
			<!--EF Jan/2017 - Campo de filtro dinamicamente formado --->
			 <span class="select">
				 <select id="fk_seguradora" name="fk_seguradora">
						<?php
						
                                               var_dump('testeyyy'); // just to locate the code easily.
						var_dump($fk_seguradora_f);
						die;
						
						
						foreach($fk_seguradora_f as $each)
						{
						?>
							<option value="<?=$each['id_seguradora']?>"><? echo $each['nome_seguradora']?></option>
						<?php
						}
						?>
				</select>
			  </span>
		</div>
	</div>
</div>

Open in new window


Debbuging, the array is correctly obtained in the view:
img001
The combo is functional but the names (nome_seguradora) doesn't appears.

img002Could you point a workaround on this?

Thanks in advance!
0
Hi Experts

Could you point a way to form a view's combo based on Codeigniter's results?

Accordingly to:

Controller's code:
public function index() {

	// SELECT/DROPDOWN - Seguradora
	$fk_seguradora = $this->cliente_corporativo_model->new_get(array('query' => 'select * from system_seguradora'));
	$dropdown[0] = 'Selecione ...';
	foreach ($fk_seguradora as $key => $value)
		$dropdown[$value->id_seguradora] = $value->nome_seguradora;

	$this->data['fk_seguradora'] = form_dropdown('fk_seguradora', $dropdown, '', 'id="id_seguradora"');
	unset($dropdown);
	
	...

Open in new window



View's code:
The values are actually "hard coded"
  <div class="row">
	<div class="col-xs-12 mb15">
		<div class="input-group">
			<span class="input-group-addon ">
				<i class="fa fa-search c-gray"></i>
			</span>
			<span class="select">
				<select id="fk_seguradora" name="fk_seguradora">
					<option value="" selected="selected">...Cliente Corporativo...</option>
					<option value="1">Ace</option>
					<option value="2">Zurich</option>
					<option value="3">Banco Safra</option>
					<option value="4">SANTANDER</option>
					....
				</select>
			</span>
		</div>
	</div>
</div>

Open in new window


I tryed to do this way:
<div class="row">
	<div class="col-xs-12 mb15">
		<div class="input-group">
			<span class="input-group-addon ">
					<i class="fa fa-search c-gray"></i>
			</span>
			<span class="select">
				<select id="fk_seguradora" name="fk_seguradora">
				
                                  // A for-each at this point makes sense?? - I guess there is a better option.
				   <option value="<?php $id_seguradora?>"><?$fk_seguradora?></option>
 
						
				</select>
			</span>
			</label>
		</div>
	</div>
</div>

Open in new window


Thanks in advance!
0
Hi Experts

Could you possibly give a help on how to configure Datatables plugin to make it correctly runs?

It's a Codeigniter project.
View code
<?php
             //datatables is a Codeigniter helper
		echo datatables(
				array(
			'id_servico' => 'ID',
			'descricao' => 'Descrição',
			  'acoes' => 'Ações',
                        // These lines must receive fake values otherwise Datatables doesn't load
			'a' => '',
			'b' => '',
			'c' => '',
			'd' => '',
			'e' => '',
			'f' => '',
		  
				),
				// Options dataTables
				array(
			'id' => 'datatables',
			'width' => '100%',
			'controller' => 'servico',
			'action' => 'datatables_list',
				),
				array(
			'like' => array(
				 'descricao'
			),
			'where' => array(
				'descricao'
			),
			'search_submit' => '.pesquisar_groups_form',
				)
		);

?>

Open in new window


Relevant part of datatables helper where the Datatable plugin is configured:
function redrawDataTables(where) {

	if (typeof table != "undefined" && typeof table != undefined && table != "") {

		$("#exemplo").empty();
		table.destroy();
	}

	if (typeof where == "undefined" || typeof where == undefined) {
		where = "";
	}
	   
	table =  $("#' . $options['id'] . '").DataTable({
		"paging":   true,
		// "pagingType": "scrolling",
		"pagingType": "full_numbers",
		// "sPaginationType": "four_button",
		"retrieve": true,
		"searching": false,
		"ordering": true,

		"order": [
			[ 
				' . $order . ', "' . $order_type . '"
			]
		],

		

Open in new window

0
I am trying to redirect the page when I click on "goback" button. Since I already have an ajax call when I click on "submit" button, I went ahead to add ajax call to "goback" button. I want to redirect the page when I click on "goback" with the data from controller. I am able to see the next page with all the data I need to display in the console, but unable to actually navigate the page. I know that ajax is expecting a response for the request it has sent but I am stuck with the navigation part. Also I am using codeigniter.
I have posted my code below.


view:


 
 <form name="uploadFile" method="post" enctype="multipart/form-data" id="upload-form">
 <p>
<div class="input-files">
  <?php
  foreach ($results as $row) {
   ?>
            <label for="methodname">Method Name:</label>
  <input type="radio" name="taskid" checked="true" id="taskid" value="<?php echo $row->taskid; ?>"/><?php echo $row->taskname; ?><br>
              <input type="radio" name="methodfields" checked="true" id="methodfields" value="<?php echo $row->methodid; ?>"/><?php echo $row->methodname; ?><br>
            <?php } ?>
 </p>
  <b>Step</b><input type="text" name="step" id="step"/><br/>
  <b>Image</b>
  <input type="file" accept="image/png, image/jpeg, image/gif" name="message" id="message" />
</div>
 <input type="button" value="Send Comment" id="submit" name="submit">
   <input class="form-control" type="button" value="Go Back" id="goback" name="goback">
  <ul id="comment"></ul>

Open in new window

0
Not a question, just a heads-up to the E-E community.  PHP 5 is circling the drain, with active support continuing only 21 more days at this writing.  Time to upgrade to PHP 7+
http://php.net/supported-versions.php

Of particular importance is the removal of MySQL, which has been deprecated for years.  More information here:
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

If your PHP framework or application depends on any version of PHP < 7.0, you may have a sudden load of technical debt, and a difficult decision to make.
1
Hi Experts

Could you point why this Codeigniter's data insertion is causing an error?

if ($this->db->insert("server_routes", $params)) {
	return $this->db->insert_id();
} else {
	return false;
}

Open in new window


Thanks in advance!

The $params array:
array(9) { ["id"]=> string(0) "" ["_name"]=> string(3) "xxx" ["_hostname"]=> string(14) "192.168.100.76" ["_port"]=> string(4) "5060" ["_providerId"]=> string(2) "13" ["_prefix"]=> string(5) "65019" ["_active"]=> string(1) "1" ["_channel"]=> string(3) "120" ["_description"]=> string(0) "" }

Open in new window


The MySQL table structure where the data must to be inserted:

CREATE TABLE server_routes (
  id int(11) NOT NULL DEFAULT 0,
  _name varchar(150) DEFAULT NULL,
  _hostname varchar(45) DEFAULT NULL,
  _port int(11) DEFAULT NULL,
  _providerId int(11) DEFAULT NULL,
  _prefix varchar(15) DEFAULT NULL,
  _active int(11) DEFAULT NULL,
  _channel int(11) DEFAULT 30,
  _description text DEFAULT NULL
)
ENGINE = INNODB
AVG_ROW_LENGTH = 327
CHARACTER SET latin1
COLLATE latin1_swedish_ci;

Open in new window

0
I am getting the above error and I am really not sure where I am going wrong. I am using Codeigniter framework. Following is my code:

Controller:

public function createtask()
      {
      
  $this->load->model('persona_model');
    $data['persona']=$this->persona_model->view();
                  $this->load->view('createtask_view', $data);
            }

Model:

function view()
      {
          $this->db->select('*');
          $this->db->from('persona');
          $query = $this->db->get();
          if($query->num_rows()>0){
          return $query->result();
          }else{
              return $query->result();
          }
      }


view:
                <table class="table">
                <thead>
              <tr>
                <th>Persona ID </th>
                <th>Firstname </th>
                <th>Lastname</th>
                </tr>
                </thead>
                <tbody>
                  <?php
                  foreach($persona as $row)
                {
                      ?>
                      <tr>
                      <td><?php echo $row->personaid; ?></td>
                      <td><?php echo $row->firstname; ?></td>
                      <td><?php echo $row->lastname; ?></td>
                  <?php      }
                  ?>
                   </tbody>


Kindly help I have been looking into this since a long time.
0
I replaced an old minisite written in classic asp with a new one built on a codeigniter platform. When I tried to create 301 redirects in ii8 they weren't implemented and resulted in codeigniter 404 pages. As a workaround I just inserted an asp redirect into all the asp pages, which was kind of tedious, but it worked. I just wanted to know how this could be better accomplished either in codeigniter or by having codeigniter to recognize the url redirect rules. As an experiment I created some url redirects from asp to php pages, which worked so that's not the problem. I think it must have something to do with codeigniter routing.
0
Hi Chris,
Thank you for your help on the last question!

I had this question after viewing Printing unique/distinct values PHP, MSSQL, Codeigniter.

In my main application Controller of 'post', I have the original method of 'show' (dropdown of faculty names)
casweb.memphis.edu/suapp-research/index.php/post/show

I also have another method of 'by_area'
casweb.memphis.edu/suapp-research/index.php/post/by_area (dropdown of research areas)

If I go to: 'http://casweb.memphis.edu/suapp-research/index.php/post/show', I get both methods, but the 'by_area' gives an error of:
Undefined Index for Research_Area and Research_Area_Prefix.

If I go to: http://casweb.memphis.edu/suapp-research/index.php/post/by_area (it works as it should)

How can I view them both through the main controller of 'post'? Or can I? I will have at least one more method for 'post' if possible.

Post.php Main Controller
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Post extends CI_Controller {
    
    public function show() {
                        
        
        $this->load->helper('form');
        $this->load->model('Post_faculty_model');  //load model
        $post_faculty = $this->Post_faculty_model->get_posts();


        $data = array();
        $data['rows'] = $post_faculty;
        $this->load->view('post_view', $data);
  

Open in new window

0
Hi Experts

Could you point how to correctly shows a Codeigniter's method reply to a view?

My try is (with no success)

jQuery code that call the Codeigniter's controller:
 $("body").on("click", ".call-ajax", function() {
          
   var id_rec = $(".id_reclamacao").val();
   var caminho = "<?php print base_url() . 'public/uploads/anexos/'; ?>";

   var postData = {
	 "id_rec": id_rec,
	 "anexo" : caminho + $(this).data("anexo")
	};

	$.ajax({
	  url: "reclamacao/delete_anexo",
	  data: postData,
	  type: "POST"
	}).done(function(resp) {
		
	  //Where I guess the reply is obtained
	  $("#result").append($("<li/>").html(resp));
	});
  });

Open in new window


Controller's code:
<?php
public function delete_anexo()
{
	try
	{
		if (!$this->input->is_ajax_request())
		{
			$this->output->set_status_header(404);
			return;
		}

		//EF 2016/Nov - 01 
		$id_reclamacao = $this->input->post('id_rec');
		$anexo = $this->input->post('anexo');


		if (!$this->anexo_model_reclamacao->delete_anexo($id_reclamacao, $anexo))
			throw new Exception("Erro ao excluir", 1);

		$alert = 'Operação Realizada com sucesso.';
		
		//Where I tried to reply to the view:
		$this->output->set_content_type('application/json')->set_output(json_encode($alert));
	}
	catch (exception $e)
	{
		$alert = $e->getMessage();
	}

	bootbox_alert($alert);
}

Open in new window



View code:

<hr>
<div class="row">
	<div class="result">
	</div>
</div>

Open in new window


Thanks in advance!
0
Hi Experts


Accordingly with some researchs a way to correctly configure date(s) when using datatables is with moment.min.js

So, folowing the examples:

Considering a Codeigniter's helper outputs to the view.

Helper's code that forms datatable

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

if (!function_exists('datatables_padrao2'))
{


    function datatables($fields, $options, $search)
    {


        $order = $cont = 4;
        $order_type = "asc";

        if (isset($options['order']))
        {

            if (isset($options['order_type']) && $options['order_type'] == 'desc')
                $order_type = 'desc';

            foreach ($fields as $field => $label)
            {

                if ($options['order'] == $field)
                {
                    $order = $cont;
                }

                $cont++;
            }


        }

        $datatables = '
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.bootstrap.css">
            <link rel="stylesheet" type="text/css" href="' . base_url() . 'public/vendor/plugins/datatables/media/css/dataTables.plugins.css">

            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/jquery.dataTables.js"></script>
            <script src="' . base_url() . 'public/vendor/plugins/datatables/media/js/dataTables.bootstrap.js"></script>
            
            <!-- 

Open in new window

0
Could you point how to correctly call a Codeigniter method from jQuery?

Accordingly to:
$("body").on("click", ".call-ajax", function() {
		// obtém o valor do link
		console.log("chamada ajax");
  
		var caminho = "http://localhost/xxxxx/public/uploads/anexos/";
	   
	   
		data = {
		  id_rec: $(this).data("id_rec"),
		  anexo: caminho + $(this).data("anexo")
		};
	
		console.log(data);
	
		// AJAX para o controller
		$.ajax({
		  url: "reclamacao/delete_anexo",
		  data: data,
		  type: "POST"
		}).done(function(resp) {
			console.log("deleção OK");
		  // Display the resposne
		  //$("#result").append($("<li/>").html(resp));
		});
	  });

Open in new window


It correctly calls
img002

But this error occurs:
img001
Controller code:
public function delete_anexo($id, $file)
{
	try
	{
		if (!$this->input->is_ajax_request())
		{
			$this->output->set_status_header(404);
			return;
		}
		if (!$this->anexo_model_reclamacao->delete_anexo($id, $file))
			throw new Exception("Erro ao excluir", 1);

		$alert = 'Operação Realizada com sucesso.';
	}
	catch (exception $e)
	{
		$alert = $e->getMessage();
	}

	bootbox_alert($alert);
}

Open in new window



Model Code:
      public function delete_anexo($id, $file) {
        $this->db->delete($this->table, array('id_reclamacao' => $id, 'file' => $file));
        return true;
    }

Open in new window



Thanks in advance!
0
Hi Experts

Could you point how to a modal view obtains a main's view control value by using jQuery and then disponibilize it to a function?

Main view
img006
50 is the id to be obtained in modal view.

jQuery modal code:
.on("edit", function(e, data) {

      // How to code here to obtain the "id" value ?
	var $form = $(this);

	$.each(data, function(field, value) {
		//console.log(field+ " - " +value);
		var
			avoid = ' . json_encode($options['edit']['avoid']) . ',
			$field = $form.find(\'[name="\' + field + \'"]\'),
			tag = ($field.length ? $field.prop("tagName").toLowerCase() : undefined)
		;
				if(field ==="anexo"){
					if(value !==null){
						$(".anexo").show();
						var link = "";
						$.each(value,function(id, valor){
							var anexo = valor.anexo;
							anexo = anexo.split("/");
							anexo = $(anexo).get(-1);
					
							
							//Excluir button must to send the id (obtained from main view) and the anexo value - still obtained
							link = link+ "<p><a href=\'"+valor.anexo+ "\' target=\'_blank\' class=\'anexo\' name=\'link\'>"+anexo+"</a><button type=\'button\'  class=\'call-ajax\' data-anexo=\'" + anexo + "\'>Excluir</button></p>";  
						
																;
						});
						$("#anexo").html(link);
					}else{
						$(".anexo").hide();
					}
				}

Open in new window


The above code (modal) produces:
img003

Function to be called by the "Excluir" button - here a Codeigniter controller must be called with 02 arguments id and anexo (still obtained)

  $("body").on("click", ".call-ajax", function() {
	// obtém o valor do link
	console.log("chamada ajax");
  

	data = {
	  anexo: $(this).data("anexo")
	};

	console.log(data);

	// AJAX para o controller
	$.ajax({
	  url: "reclamacao/delete_anexo",
	  data: data,
	  type: "POST"
	}).done(function(resp) {
		console.log("deleção OK");
	  // Display the resposne
	  //$("#result").append($("<li/>").html(resp));
	});
  });

Open in new window


Thanks in advance!
0
Hi Experts

Could you point how to put a functional button at the right side of the links by using jQuery?

Plus - this button needs to call, by Ajax, a PHP Codeigniter's controller to perform a deletion (Excluir means deletion).

Accordingly to:
img001
jQuery code used:
if(field ==="anexo_v"){
	if(value !==null){
		$(".anexo_v").show();
		var link = "";
		$.each(value,function(id, valor){
			var anexo = valor.anexo;
			anexo = anexo.split("/");
			anexo = $(anexo).get(-1);
			//console.log(valor.anexo);
			link = link+"<p><a href=\'"+valor.anexo+ "\' target=\'_blank\'>"+anexo+"</a></p>";                                             ;
		});
		$("#anexo").html(link);
	}else{
		$(".anexo").hide();
	}
}

Open in new window


Thanks in advance!
0
I have a very messy sql statement joining 4 different tables. I need distinct/unique values from one column. My statement is pulling all of the information I need but now I need to print out the unique value from one column with all values from the other columns.

Using Codeigniter controller, model and view.

What it accomplishes:
Research Area would be unique to each faculty member while (several) Research Area Topics are displayed under the Research area. (the $Faculty_Research_Match is determined from drop down menu with faculty members information)

---------------------------------------------------------------------------------------------------------------------------------------------------------------

Model:
public function post_it_now($Faculty_Research_Match) {
        $this->load->database();        

$query = $this->db->query("SELECT * FROM suapp.FACULTY

        JOIN suapp.RESEARCH_MATCH on suapp.RESEARCH_MATCH.Faculty_UUID = suapp.FACULTY.Faculty_UUID JOIN suapp.AREA_TOPIC on suapp.AREA_TOPIC.Area_Topic_Code = RESEARCH_MATCH.Area_Topic_Code
   
        JOIN suapp.RESEARCH_AREA on suapp.RESEARCH_AREA.Research_Area_Prefix = LEFT (suapp.AREA_TOPIC.Area_Topic_Code, 2)  
       
        WHERE suapp.FACULTY.Faculty_UUID = '".$Faculty_Research_Match."'");
{
        $rows = $query->result_array();
        return $rows;
}
    }

View:
foreach($rows as $row){
   
    print "<table>";
    print "<tr><td>";
 …
0
$query = $this->my_model->get_the_customer_orders();

$data = $query->result(); (converts the PDO output to an array of objects or db rows)

echo json_encode($data);

works great, and a front end javascript parses everything out a build a big beautiful table (datatables js).  Except when there is malicious script injected into the DB, it passed straight though to the browser.

The problem is I want to use the fancy xss_clean method in CodeIgniter to scrub the data before rendering.  Like this:

$scrubbedData = $this->security->xss_clean($data); // remember $data is an array of objects aka db rows
// produces an error.. basically the xss_clean method can't handle objects.. just strings and arrays.

It seems a foreach loop to iterate through $data and apply xss_clean to each row column before json encode may work but it seems sooooo bloaty and inefficient.  

Am I missing some general design pattern to filter xss more elegantly?

FYI I use MVC views for nearly every other page in the project, this is a unique case of rendering page content with javascript.  And I can't figure out how to xss clean the content efficiently.  I may have to rewrite and use a php view instead of rendering via ajax in this page.  Anyway can someone see another solution?
0
It seems to me XSS attacks insert malicious scripts/elements/links into the server side output before it is rendered by the browser.  From what I understand the user opens the page and the embedded exploit takes action within the browser.

CodeIgniter 3.1 has a security class  and a method xss_clean() that can be used to scrub data, presumably output data before rendering in keeping with the definition of an xss attack.

In the config there is a deprecated setting to apply xss filtering globally.  It is accompanied by a warning that it is deprecated.  Ok so don't use the global xss filtering, I get it.

So does this mean that in every input from ajax or forms that hit the controller via $this->post->input('my_var'); needs to be somehow sanitized?  How?

I recall reading somewhere that  CodeIgniter automatically 'sanitizes' post inputs when called using the input class.  But I can't find any evidence of that in the documentation.   https://www.codeigniter.com/user_guide/libraries/input.html

It simply says security filtering input is called automatically when a new controller is invoked but I still can't see any clear statement that some kind of filtering or sanitizing takes place on post inputs.  Can someone help me better understand how this is taking place automatically.

As I'm typing this I'm thinking that I could have tested it manually to check for input sanitizing and I will, but I'm interested in some expert comments on this.

Thanks!
0

CodeIgniter

44

Solutions

59

Contributors

CodeIgniter is an open-source software rapid development web framework used to build dynamic websites with PHP. The software is partly based on the model–view–controller (MVC) pattern, although models and views are optional. It is typically recognized for its speed when compared to other PHP frameworks.

Top Experts In
CodeIgniter
<
Monthly
>