This is very simple to understand
Image Class
<?php
class Image extends Zend_Db_Table_Abstract {
protected $_name = 'images';
public function getList() {
return $this->fetchAll();
}
}?>
My PHP Code
<?php
require 'config.php';
$imgTable = new Image(); // Create Object
$imgList = $imgTable->getList(); // fetch Data
$template = new Template('portfolio'); // Initialize Template and tell which template to pick
$template->imgList = $imgList; // set template variable
$template->render(); // Generate Template output
?>
I can access template variable inside template using $this
Below code is from inside the template
$xback = 0;
foreach ($this->imgList as $images) {
echo 'imageArray[' . $xback . '] = "' . $images['sef'] . '";';
$xback++;
}
?>
.......
<?php
foreach ($this->imgList as $images) {
?>
<div class="portfolio_item">
<img src="<?php echo PATH_WEB . $images['image_thumb'] ?>" height="146" width="209" />
<div class="title"><?php echo $images['image_title'] ?></div>
<div class="right link">
View Details
</div>
</div>
<?php
}
?>
Above code is working fine, but below some few lines, I have to iterate over the same data again dont output any thing. If I comment the first one, 2nd starts working.
First one is to create the JS array and is in head section,
Second part is in HTML to display images
I hope its a pointer issue, I may have to set the loop current item to start, but I am not understanding it right now .... reset($this->imgList) didnt worked
please help
I think it has something to do with the fetchAll call, try this:
<?php
class Image extends Zend_Db_Table_Abstract {
protected $_name = 'images';
protected $images;
public function getList() {
// Employ lazy loading pattern to load images if they aren't set yet
if (!isset($this->$images)) {
$this->images = $this->fetchAll();
}
return $this->images;
}
}?>
Related
Controller has index() method and display() method.
Method index displays the image. and this method called display() doesn't display the images.
Both methods are in same controller.
Both methods are calling the same view file called
$this->load->view('home/portfolio2');
.
index() method is displaying the image but display() method not displaying the image.
index method code is
public function index() { //$this->load->view('images/homeimage'); //home image.
$this->load->view('home/portfolio2');
$this->load->view('home/header');
$this->load->view('home/viewcategory');
$result['msg'] = $this->W_model->latestupdates();
$result['title'] = 'latest updated';
if($result['msg'] == NULL) {
echo "check for albums in DB";
}else{
$this->load->view('home/latestsongsupdated', $result);
}
$this->load->view('home/footer');
}
display method code is
Public function displayalbums($albums, $lang){
$result['title'] = $lang;
$result['msg'] = $this->W_model->displayalbum($albums);
if($result['msg'] == NULL) { ?>
<h3 style = "margin-left: 20px;">
<?php echo "Songs will be updated soon, Please check for other songs"; ?>
</h3> <?php
} else{
$this->load->view('home/portfolio2');
$this->load->view('home/viewcategory');
$this->load->view('home/albums', $result);
}
}
Any advise, help will be more appreciated.
The correct syntax for image src is:
<?php echo base_url('assets/images/glow_in_worship_by_riyovincent-d571aon.jpg'); ?>
If that does not work echo base_url() somewhere. It should point to localhost/worship if your entire CI is in an htdocs or HTML subfolder that's called workshop. If it doesn't then you should edit your base_url correctly in the config as http://localhost/workship.
You can also use the image helper to generate the image tag (load HTML helper):
<?php echo img('assets/images/glow_in_worship_by_riyovincent-d571aon.jpg'); ?>
Note: this method also requires the base_url to be set correctly.
#raviraj123456
Use the full URL like this: 'http://www.example.com/assets/images/…; in src of the img tag and it will work.
I am parsing a JSON Object and using a foreach loop to output the data.
function do_api_call() {
$place_id = get_theme_mod('place_id_setting_field');
$url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" . $place_id . "&key=myapikey";
$data = file_get_contents($url);
$rev = json_decode($data, true);
$reviews = $rev["result"]["reviews"];
foreach($reviews as $review) {
$review_snippet = $review["text"];
echo $review_snippet . '<br>';
}
}
This works fine when I call it within an HTML element with:
<?php echo do_api_call() ?>
The short of it is that I get back 5 reviews from this loop and I need each review to go to their own html element in a different file called reviews.php, this file contains 5 unique bootstrap cards with a div that needs to hold a unique review so I need to output a unique review into each of these cards.
Like so:
<div> review 1 text </div>
<div> review 2 text </div>
<div> review 3 text </div>
<div> review 4 text </div>
<div> review 5 text </div>
You access a direct review with $rev["result"]["reviews"][0] (for the first) $rev["result"]["reviews"][1] (for the second) etc. So you can pass which review as a function arg.
However to cut down on re-loading an external source with every call of the function, you may want to do the data loader outside the function:
$place_id = get_theme_mod('place_id_setting_field');
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid='.
$place_id .'&key=myapikey';
$data = file_get_contents($url);
$rev = json_decode($data,true);
$reviews = $rev['result']['reviews'];// this is now setup and ready to use
And then setup the anonymous function using the global (php 5.3+):
$get_review = function ($r) use (&$reviews) {
if (isset($reviews[$r])) {
return '<div>'. $reviews[$r]['text'] .'<div>';
}
return '';// no review to return
};
Then down in your html where you want to begin outputting them, you call it as such (note the $ is intentional with anonymous functions assigned to variables):
<body>
blah blah other stuff
<?php echo $get_review(0);?>
more blah
<?php echo $get_review(1);?>
</body>
Or if you need to loop on how many reviews you have:
<body>
<?php for($r=0;$r < count($reviews);$r++) { echo $get_review($r); } ?>
</body>
If you are afraid of using anonymous functions as I have above, you can adjust it to this instead:
function get_review ($r,&$reviews) {
if (isset($reviews[$r])) {
return '<div>'. $reviews[$r]['text'] .'<div>';
}
return '';// no review to return
}
// call it as thus
echo get_review(0,$reviews);
echo get_review(1,$reviews);
// etc
Class Method:
Of course you COULD also turn this into a small class object, where you first load_api, then get_review as methods of the class:
class Reviews {
public static $reviews;
public static function load_api() {
$place_id = get_theme_mod('place_id_setting_field');
$url = 'https://maps.googleapis.com/maps/api/place/details/json?placeid='.
$place_id .'&key=myapikey';
$data = file_get_contents($url);
$rev = json_decode($data,true);
self::$reviews = $rev['result']['reviews'];// this is now setup and ready to use
}
public static function get_review($r) {
if (isset(self::$reviews[$r])) {
return '<div>'. self::$reviews[$r]['text'] .'<div>';
}
return '';// no review to return
}
}
// to initialize
Reviews::load_api();
// to call and output
echo Reviews::get_review(0);
I used the same code (below) in both front and backend, but the pagination is not working in the admin side.
====================MODEL=PART===========================
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
class CiieModelOrders extends JModelList
{
public function getItems()
{
// Invoke the parent getItems method to get the main list
$items = parent::getItems();
return $items;
}
protected function getListQuery()
{
$db = $this->getDbo();
$query = $db->getQuery(true);
$query->select('title');
$query->from('q2b7v_menu');
return $query;
}
}
====================VIEW=PART===========================
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
class CiieViewOrders extends JView {
protected $state;
protected $item;
protected $form;
protected $params;
public function display($tpl = null) {
$items = $this->get('Items');
$pagination = $this->get('Pagination');
$this->items = $items;
$this->pagination = $pagination;
parent::display($tpl);
}
}
==================TEMPLATE=PART=========================
<?php
JHtml::_('behavior.keepalive');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
//Load admin language file
$lang = JFactory::getLanguage();
$lang->load('com_ciie', JPATH_ADMINISTRATOR);
?>
<div>
<table>
<?php
foreach($this->items as $item){
echo "<tr><td>".$item->title."</td></tr>";
}
?>
</table>
<?php echo $this->pagination->getListFooter(); ?>
</div>
This works fine in the front end (site side).
Session output-> [orders] => stdClass Object ( [ordercol] => [limitstart] => 0 )
Link html/url (for next button)-> <a title="Next" href="/NewJoomla/index.php/component/ciie/?view=other&start=20" class="pagenav">Next</a>
I put the same code in Admin side (backend), and it shows all the paginatiion buttons and everything. But the buttons don't function at all. They simple take me to the top of the page. When I check the links (for example 'next' button) I see this:
Next
(As you can see href attribute value is empty(#).)
Session output-> [orders] => stdClass Object ( [ordercol] => )
(Here also 'limitstart' value doesn't exist at all.
I tried this in different fresh Joomla installations too but the same problems repeats again.
Is there any thing I missed?
Finally I sorted it out! It was a silly mistake!
In the template, I didn't put the list content inside a <form> tag. getListFooter() function shows the pagination buttons, but when clicked the action is not submitted anywhere. I corrected the code as shown below and it worked.
==========TEMPLATE=PART====================
...
<div>
<form action="<?php echo JRoute::_('index.php?option=com_ciie&view=orders'); ?>" method="post" name="adminForm">
<table>
<?php
foreach($this->items as $item){
echo "<tr><td>".$item->title."</td></tr>";
}
?>
</table>
<?php echo $this->pagination->getListFooter(); ?>
</form>
</div>
Thank you all.
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);
I am trying to get the following function to run when the link is clicked and then load the previous page, but I seem to end up with a blank page with no php errors:
View:
<?php if(is_array($get_images)): ?>
<?php foreach($get_images as $image): ?>
<img src ="<?=base_url()?>includes/uploads/gallery/thumbs/<?=$image['thumbname']?>" alt="<?= $image['description']?>"> Delete
<?php endforeach; ?>
<?php endif; ?>
Controller:
function delete($id) {
$id = $this->uri->segment(3);
$this->image_model->deleteImage($id);
$page['get_images'] = $this->image_model->getImages();
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = 'Delete Gallery Image';
$data['content'] = $this->load->view('admin/deleteimage',$page,TRUE);
}
}
Firstly, a destructive thing such as deleting an image should be POST, not GET.
As for the code, something like this should work (assuming that last closing brace means your function is a class method)...
// However you extract params in your framework.
$id = $request->getParam('id');
// Instantiate the class.
$controller = new ImageController;
// Call the method.
$controller->delete($id);