where to process mysql queries in codeigniter? - php

Where should we process mysql queries in CodeIgniter application?
For example in a simple project we do like this :
for controller:
class Blog extends CI_Controller {
function posts(){
$data['query'] = $this->blog_model->index_posts();
$this->load->view('blog_view', $data);
}
}
and in view :
<?php
while ($post = mysql_fetch_object($query)):
?>
<div>
<p><?= $post->body; ?></p>
</div>
<?php endwhile; ?>
But, if we want to do something with body of post before print where should it be done?
For example, I want to write a function that formats the body of post and pass the body to it before doing echo.
Where should it be placed according to CoeIgniter's structure and recommended practices? (best option)
in the controller? (if so , how to use it)
in the view?
write a helper?
other approaches ?

Here's what is recommended:
Controller:
function posts() {
$this->load->model("blog_model");
$data['rows'] = $this->blog_model->index_posts();
$this->load->view("blog_view", $data);
}
Model: (blog_model.php)
function index_posts() {
$this->load->database();
$query = $this->db->get('your_table');
$return = array();
foreach ($query->result_array() as $line) {
$line['body'] = ... do something with the body....
$return[] = $line;
}
return $return;
}
View: (blog_view.php)
<?php foreach ($rows as $line): ?>
<div>
<p><?php echo $line['column']; ?></p>
</div>
<?php endforeach; ?>
Basically what happens is your model returns a multidimensional array that is passed the view and processed using a foreach() loop.
Good luck!

If you want to reuse that function create a helper. If you want this function only once put it in your controller and call from that controller.
Models are just for accessing database or maybe in few other cases, but mostly just for accessing things in database or editing, deleting etc. and sending the result to controller for further processing.
In your case I would stick with helper.
E.g. you will create a file top_mega_best_functions.php and put it inside helpers folder.
Than you write ther e.g. something like
function red_text($input) {
echo '<span style="color: red;">';
echo $input;
echo '</span>';
}
Then load the helper in your autoloader file or load before using.
And use in your view or controller like
$blablabla = "This text will be red";
red_text($blablabla);

Related

Codeigniter passing data controller to view

Here is my controller:
class CommonController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('common_model'); //load your model my model is "common model"
}
public function add_work(){
$names = $_POST['name'];
$works = $_POST['work'];
$allValues = array(); // array to contains inserted rows
foreach($names as $key => $name){
$name= "your specified name";
$insertdata = array();
$insertdata['work'] = $works[$key];
$insertdata['name'] = $name;
$this->common_model->insert($insertdata);
array_push($allValues,$insertdata);
//$insert = mysql_query("INSERT INTO work(name,work) values ( '$name','$work')");
}
foreach($allValues as $insertRow){
echo $insertRow['work'];
echo $insertRow['name'];//this shows data well. but how to pass data in view.php
}
//view code will add here to show data in browser
}
Basically I want to pass all data to view.php for printing or exporting purpose. How can I do so.
To load a view you should do like this.
$this->load->view("filename");
If you want to pass data to view, you should do like this.
$this->load->view("filename",$data);
$data should have all parameters which you want to print in view.
The syntax goes like this.
$this->load->view("filename","data to view","Returning views as data(true / false");
If third parameter is true, view will come as data. It will not go to browser as output.
Edit:
Change
$this->load->view('print_view',$insertdata);
to
$data['insertdata'] = $insertdata;
$this->load->view('print_view',$data);
For more info, check this link
How CI Classes Pass Information and Control to Each Other
Calling Views
We will see.how the controller calls a view and passes data to it:
First it creates an array of data ($data) to pass to the view; then it loads and calls the view in the same expression:
$this->load->view('testview', $data);
You can call libraries, models, plug-ins, or helpers from within any controller, and models and libraries can also call each other as well as plug-ins and helpers.
However, you can't call one controller from another, or call a controller from a
model or library. There are only two ways that a model or a library can refer back to a controller:
Firstly, it can return data. If the controller assigns a value like this:
$foo = $this->mymodel->myfunction();
and the function is set to return a value, then that value will be passed to the variable $foo inside the controller.
//sample
public function display()
{
$data['text_to_display'] = $this->text_to_display;
$data['text_color'] = $this->text_color;
$this->load->view('display_view',$data);
}
Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view
loading method. Here is an example using an array:
$data = array(
’title’ => ’some’,
’heading’ => ’another some’,
’message’ => ’and another some’
);
$this->load->view(’view’, $data);
And here’s an example using an object:
$data = new Someclass();
$this->load->view(’view’, $data);
Sending Multiple Dimensional array
if we pull data from your database it will typically be
in the form of a multi-dimensional array.
<?php
class foo extends CI_Controller {
public function index()
{
$data[’Books’] = array(’POEAA’, ’TDD’, ’Clean C’);
$data[’title’] = "Title";
$data[’heading’] = "Heading";
$this->load->view(’view’, $data);
}
}
in view
<html>
<head>
<title><?php echo $title;?></title>
</head>
<body>
<h1><?php echo $heading;?></h1>
<h3>My Books List</h3>
<ul>
<?php foreach ($Books as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</body>
</html>
More Learning
NOTE:
There is a third optional parameter lets you change the behavior of the method so that it returns data as a string rather
than sending it to your browser.The default behavior is false, which sends it to your browser. Remember to
assign it to a variable if you want the data returned:
$string = $this->load->view(’view’, ’’, TRUE);
Above will not solve your problem directly but definetly help in understanding concepts.

cakephp call a controller function in view file

My method is
public function topmenu($parentsid=null){
$this->layout =false;
$category_tree = $this->Categorymaster->find('all',array('order'=>'Categorymaster.lft ASC','conditions'=>array('Categorymaster.parent_id'=>$parentsid)));
echo '<ul class="sub-menu" role="menu">';
foreach($category_tree as $parentval){
echo '<li>'.$parentval['Categorymaster']['name'].'</li>';
$id = $parentval['Categorymaster']['id'];
$haschild = $this->Categorymaster->children($id, true);
if (!empty($haschild)) {
$this->topmenu($id);
}
}
echo '</ul>';
$this->set(compact('category_tree'));
$this->render('topmenu');
}
I get output from controller
I am trying to use a foreach loop in my topmenu.ctp file but as cakephp
is mvc it gives error at the lines
$haschild = $this->Categorymaster->children($id, true);
if (!empty($haschild)) {
$this->topmenu($id);
}
so how can it use topmenu() method in .ctp file so that i can show it in my menu or any other alternative.
First of all its never a good practice to call controller method directly in ctp (view) file.
If you still want to do this, try to call like this:-
Controller name::(scope resolution operator) function name(parameters).
Note:-Make sure that your method is public.

CodeIgniter fatal error: Call to a member function display_clients() on a non-object

I am writing a program that basically does stuff with a database, I am having trouble with some of the functionality though, this is what it is supposed to do
public function clist() {
$this->load->model('list_model');
$fields = $this->list_model->listcli();
if ($fields === $this->list_model->listcli()) {
$fieldl = $fields;
$this->load->view('clientlist');
$this->clientlist->display_clients($fieldl);
}
}
This loads the model which looks like this:
public function listcli()
{
$this->db->list_fields('clients');
}
}
Then runs the model function listcli so that it will list all the fields in the clients database and puts the value into $fields I then call it fieldl and load a view that will show the data, the view looks like this:
<html>
<body>
<p> sup </p>
<?php
function display_clients($fieldl)
{
?>
<html>
<body>
<p> sup2 </p>
<ul>
<?php
foreach ($fieldl as $l) {
?>
<li>
<?php echo $l;?>
</li>
<?php
}
}
Then calls the function inside the view and passed the data from $fieldl into it.
but I am getting the error " Call to a member function display_clients() on a non-object in /codeigniter/src/application/controllers/clientlist.php on line 40"
line 40 is
$this->clientlist->display_clients($fieldl);
Can you help? Please and thank you.
(I know this kind of question has been asked before but they are always very specific to the code at hand so doesn't help me, I am really new to CodeIgniter so if you can keep any answer relatively simple I will be grateful).
I needed to use the second parameter possible to pass my data over into the view, not my own makeshift solution for it, CI accepts an object as a second parameter for the CI_Loader::view()
Why can't you prepare the list in the controller and pass it to view via $data array?
$my_list = '<ul>';
foreach ($fieldl as $l) {
$my_list .= '<li>'.$l.'</li>';
}
$my_list .= '</ul>';
$data['my_list'] = $my_list;
then you can access it in view as $my_list. Just echo it where you need it.
EDIT:
AS per your own answer, yes - exactly. Using example above you would pass the $data to view as the second parameter:
$this->load->view('my_view',$data);
Then in the View, you access $data['my_list'] as $my_list, $data['foo'] as $foo etc.

How to display 'tree' data in the view in Cake PHP

I am doing the tree tutorial and would like to display the data in a view and wrap it in html etc. I am new to Cake PHP and this has been a bit of a pain. Below is an example of what I've tried. In short, I figure I could assign the output to a variable using set. I am doing everything wrong.
Controller
<?php
class CategoriesController extends AppController {
public function index() {
$this->set('output', $this->Category->generateTreeList(null, null, null, ' '));
}
}
?>
View
<?php foreach ($output as $data): ?>
<div><?php echo $data['Category']['name']; ?></div>
<?php endforeach; ?>
<?php unset($data); ?>
unlike other find methonds, generateTreeList doesen't return a named array but a plain array with numeric indexes
try print_r($output) and you'll see how the array is formatted and how you can use it in your view
to show your data, in your foreach cicle you just have to do this
echo $data;

Lithium PHP, MongoDB and form helpers for arrays

I'm trying to create an edit form using Lithium to edit some MongoDB data. My data (produced by another tool) looks like this:
{
"thing_a" : "value_a",
"thing_b" : "value_b",
"settings" :
{
"sub_thing_a" : ["sub_value_a", "sub_value_b"]
}
}
The problem I'm having is with the array 'sub_thing_a' in 'settings'. I need to display a text box for each value so I can edit them and save them back. The ultimate aim here is to use some jQuery to add/delete text boxes to/from the form and then values from the array - but for now I'm trying to just get a simple version working that will let me edit the values and save them away.
My model is really simple:
<?php
namespace app\models;
class Test extends \lithium\data\Model {
protected $_meta = array('source' => 'test');
}
?>
and the controller likewise:
<?php
namespace app\controllers;
use app\models\Test;
class TestsController extends \lithium\action\Controller {
public function index() {
$tests = Test::all();
return compact('tests');
}
public function edit($id=null) {
if(isset($id)) {
$test = Test::find($id);
} else {
$test = Test::create();
}
if ($this->request->data) {
if ($test->save($this->request->data)) {
$this->redirect('/tests/index');
}
}
return compact('test');
}
}
?>
Problems start with the edit form - As I have it now, it will display the values of my array, but the data does not get written correctly. Any clues as to how I should approach this? (Note: As I mentioned earlier, I will need to produce a dynamic version of this that allows me to add/delete text boxes to/from the form, so I do need to be able to take some sort of control of the helper - in case there is some really easy 'convention' way of doing this.)
edit.html.php:
<?=$this->form->create($test); ?>
<?=$this->form->field('thing_a'); ?>
<?php foreach ($test->settings->sub_thing_a as $i=>$elem): ?>
<?=$this->form->field('settings.sub_thing_a',array('label'=>'thing', 'value'=>$test->settings->sub_thing_a[$i]));?>
<?php endforeach; ?>
<?=$this->form->submit('save'); ?>
<?=$this->form->end(); ?>
and index.html.php (for completeness)
<?php foreach($tests as $test): ?>
<h2><?=$this->html->link($test->thing_a,'/tests/edit/'.$test->_id); ?></h2>
<?php foreach($test->settings->sub_thing_a as $item): ?>
<h4><?=$item ?></h4>
<?php endforeach; ?>
<?php endforeach; ?>
Ok, so in the end, it was (of course) quite simple. in the edit.html.php file we can simply write:
<?=$this->form->field('settings[sub_thing_a][]',array('value'=>$test->settings->sub_thing_a[$i]));?>
The settings[sub_thing_a][] creates the array containing an array of the string values from the form.

Categories