joomla 1.7 : overriding pagination.php not working - php

I installed joomla 1.7(window/xampp/php 5.3) and my current template is beez_20. I have to override the pagination.php and to do so I copied the pagination.php from
\libraries\joomla\html
to
\templates\beez_20\html. When I reload the home page, I am getting a broken template as in the following picture.
I get the normal page when I remove the pagination.php from the html folder. I believe this is the correct method to override the pagination.php
what is missing ? need to change any configuration ? please post your comments
Thanks in advance

I do belive this is the correct way to do it...
Here is a pagnation.php for you to try with (works for me):
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
/**
* This is a file to add template specific chrome to pagination rendering.
*
* pagination_list_footer
* Input variable $list is an array with offsets:
* $list[limit] : int
* $list[limitstart] : int
* $list[total] : int
* $list[limitfield] : string
* $list[pagescounter] : string
* $list[pageslinks] : string
*
* pagination_list_render
* Input variable $list is an array with offsets:
* $list[all]
* [data] : string
* [active] : boolean
* $list[start]
* [data] : string
* [active] : boolean
* $list[previous]
* [data] : string
* [active] : boolean
* $list[next]
* [data] : string
* [active] : boolean
* $list[end]
* [data] : string
* [active] : boolean
* $list[pages]
* [{PAGE}][data] : string
* [{PAGE}][active] : boolean
*
* pagination_item_active
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* pagination_item_inactive
* Input variable $item is an object with fields:
* $item->base : integer
* $item->link : string
* $item->text : string
*
* This gives template designers ultimate control over how pagination is rendered.
*
* NOTE: If you override pagination_item_active OR pagination_item_inactive you MUST override them both
*/
function pagination_list_footer($list)
{
// Initialize variables
$lang =& JFactory::getLanguage();
$html = "<div class=\"list-footer\">\n";
if ($lang->isRTL())
{
$html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>";
}
else
{
$html .= "\n<div class=\"limit\">".JText::_('Display Num').$list['limitfield']."</div>";
$html .= $list['pageslinks'];
$html .= "\n<div class=\"counter\">".$list['pagescounter']."</div>";
}
$html .= "\n<input type=\"hidden\" name=\"limitstart\" value=\"".$list['limitstart']."\" />";
$html .= "\n</div>";
return $html;
}
function pagination_list_render($list)
{
// Initialize variables
$lang =& JFactory::getLanguage();
$html = "<div class=\"pagination\"><ul>";
// Reverse output rendering for right-to-left display
if($lang->isRTL())
{
$html .= "<li class=\"pagination-start\">".$list['start']['data']."</li>";
$html .= "<li class=\"pagination-prev\">".$list['previous']['data']."</li>";
$list['pages'] = array_reverse( $list['pages'] );
foreach( $list['pages'] as $page ) {
if($page['data']['active']) {
// $html .= '<strong>';
}
$html .= "<li>".$page['data']."</li>";
if($page['data']['active']) {
// $html .= '</strong>';
}
}
$html .= "<li class=\"pagination-next\">".$list['next']['data']."</li>";
$html .= "<li class=\"pagination-end\">".$list['end']['data']."</li>";
// $html .= '«';
}
else
{
foreach( $list['pages'] as $page )
{
if($page['data']['active']) {
// $html .= '<strong>';
}
$html .= "<li>".$page['data']."</li>";
if($page['data']['active']) {
// $html .= '</strong>';
}
}
}
$html .= "</ul></div>";
return $html;
}
?>

You should not override the entire pagination.php in the manner you tried. You can only override certain functions. The reason you are seeing this page is because if you copied the entire pagination.php file with out changing anything, so you are re-declaring the JPagination class and you can't do that.
When you are try to make changes to the pagination.php you should only re-write the functions you wish to override not copy the entire file.
Please check out this article it's a little dated but the information still applies even in J! 2.5
http://docs.joomla.org/Understanding_Output_Overrides

Related

codeigniter - Call to a member function query() on a non-object

I'm using xampp 1.77 version, codeigniter 1.7.2 with flexigrid.
I follow step by step this tutorial https://gembelzillonmendonk.wordpress.com/2010/06/28/flexigrid-and-codeigniter-with-advanced-searching-with-example/#comment-353 but I don't understand which code must have flexigrid.php in CI_Folder\system\application\controllers\flexigrid.php.
My flexigrid.php code is this:
<?php
class Flexigrid extends Controller {
function Flexigrid ()
{
parent::Controller();
$this->load->helper('flexigrid');
}
function index()
{
//ver lib
$this->load->model('ajax_model');
$records = $this->ajax_model->get_select_countries();
$options = '';
foreach( $records as $v ) {
$options .= $v['name'] . ';';
}
$options = substr($options, 0, -1);
/*
* 0 - display name
* 1 - width
* 2 - sortable
* 3 - align
* 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
*/
$colModel['id'] = array('ID',40,TRUE,'center',2);
$colModel['iso'] = array('ISO',40,TRUE,'center',0);
$colModel['name'] = array('Name',180,TRUE,'left',1);
$colModel['printable_name'] = array('Printable Name',120,TRUE,'left',1,'options' => array('type' => 'date'));
$colModel['iso3'] = array('ISO3',130, TRUE,'left',1, 'options' => array('type' => 'select', 'edit_options' => $options));
$colModel['numcode'] = array('Number Code',80, TRUE, 'right',1, 'options' => array('type' => 'select', 'edit_options' => ":All;AND:AND;KK:KK;RE:RE"));
$colModel['actions'] = array('Actions',80, FALSE, 'right',0);
/*
* Aditional Parameters
*/
$gridParams = array(
'width' => 'auto',
'height' => 400,
'rp' => 15,
'rpOptions' => '[10,15,20,25,40]',
'pagestat' => 'Displaying: {from} to {to} of {total} items.',
'blockOpacity' => 0.5,
'title' => 'Hello',
'showTableToggleBtn' => true
);
/*
* 0 - display name
* 1 - bclass
* 2 - onpress
*/
$buttons[] = array('Delete','delete','test');
$buttons[] = array('separator');
$buttons[] = array('Select All','add','test');
$buttons[] = array('DeSelect All','delete','test');
$buttons[] = array('separator');
//Build js
//View helpers/flexigrid_helper.php for more information about the params on this function
$grid_js = build_grid_js('flex1',site_url("/ajax"),$colModel,'id','asc',$gridParams,$buttons);
$data['js_grid'] = $grid_js;
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('flexigrid',$data);
}
function example ()
{
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('example',$data);
}
}
?>
When i type http://127.0.0.1/flexiadvanced/index.php/flexigrid browser give me a error:
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\flexiadvanced\system\application\models\ajax_model.php on line 34
this is the code of ajax_model.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Eye View Design CMS module Ajax Model
*
* PHP version 5
*
* #category CodeIgniter
* #package EVD CMS
* #author Frederico Carvalho
* #copyright 2008 Mentes 100Limites
* #version 0.1
*/
class Ajax_model extends Model
{
/**
* Instanciar o CI
*/
public function Ajax_model()
{
parent::Model();
$this->CI =& get_instance();
}
public function get_select_countries()
{
//Select table name
$table_name = "country";
//Build contents query
$separator = (string) ',';
//$this->db->select('concat(iso3, concat('. addcslashes($separator) .', iso3))')->from($table_name);
$query = $this->db->query("select concat(iso3, concat(':', iso3)) as name from country where iso3 is not null");
//Get contents
return $query->result_array();
}
public function get_countries()
{
//Select table name
$table_name = "country";
//Build contents query
$this->db->select('id,iso,name,printable_name,iso3,numcode')->from($table_name);
$this->CI->flexigrid->build_query();
//Get contents
$return['records'] = $this->db->get();
//echo $this->db->last_query();
//Build count query
$this->db->select('count(id) as record_count')->from($table_name);
$this->CI->flexigrid->build_query(FALSE);
$record_count = $this->db->get();
$row = $record_count->row();
//Get Record Count
$return['record_count'] = $row->record_count;
//Return all
return $return;
}
/**
* Remove country
* #param int country id
* #return boolean
*/
public function delete_country($country_id)
{
$delete_country = $this->db->query('DELETE FROM country WHERE id='.$country_id);
return TRUE;
}
}
?>
My database is called country and database table is called also country. This is information in CI_Folder\system\application\config
$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "country";
$db['default']['dbdriver'] = "mysql";
Can you help me to write correct code inside flexigrid.php?
This is my code for CI_Folder\system\application\helpers\flexigrid_helper.php but is correct?
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Flexigrid CodeIgniter implementation
*
* PHP version 5
*
* #category CodeIgniter
* #package Flexigrid CI
* #author Frederico Carvalho (frederico#eyeviewdesign.com)
* #version 0.3
* Copyright (c) 2008 Frederico Carvalho (http://flexigrid.eyeviewdesign.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
if (! function_exists('build_grid_js'))
{
/**
* Build Javascript to display grid
*
* #param grid id, or the div id
* #param url to make the ajax call
* #param array with colModel info:
* * 0 - display name
* * 1 - width
* * 2 - sortable
* * 3 - align
* * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
* * 5 - hidden (TRUE or FALSE, default is FALSE. This index is optional.)
* #param array with button info:
* * 0 - display name
* * 1 - bclass
* * 2 - onpress
* #param default sort column name
* #param default sort order
* #param array with aditional parameters
* #return string
*/
function build_grid_js($grid_id,$url,$colModel,$sortname,$sortorder,$gridParams = NULL,$buttons = NULL)
{
//Basic propreties
$grid_js = '<script type="text/javascript">$(document).ready(function(){';
$grid_js .= '$("#'.$grid_id.'").flexigrid({';
$grid_js .= "url: '".$url."',";
$grid_js .= "dataType: 'json',";
$grid_js .= "sortname: '".$sortname."',";
$grid_js .= "sortorder: '".$sortorder."',";
$grid_js .= "usepager: true,";
$grid_js .= "useRp: true,";
//Other propreties
if (is_array($gridParams))
{
//String exceptions that dont have ' '. Must be lower case.
$string_exceptions = array("rpoptions");
//Print propreties
foreach ($gridParams as $index => $value) {
//Check and print with or without ' '
if (is_numeric($value)) {
$grid_js .= $index.": ".$value.",";
}
else
{
if (is_bool($value))
if ($value == true)
$grid_js .= $index.": true,";
else
$grid_js .= $index.": false,";
else
if (in_array(strtolower($index),$string_exceptions))
$grid_js .= $index.": ".$value.",";
else
$grid_js .= $index.": '".$value."',";
}
}
}
$grid_js .= "colModel : [";
//Get colModel
foreach ($colModel as $index => $value) {
$grid_js .= "{display: '".$value[0]."', ".($value[2] ? "name : '".$index."', sortable: true," : "")." width : ".$value[1].", align: '".$value[3]."'".(isset($value[5]) && $value[5] ? ", hide : true" : "")."},";
//If item is searchable
if ($value[4] != 0)
{
//Start searchitems var
if (!isset($searchitems))
$searchitems = "searchitems : [";
$options = '';
if (isset($value['options'])) {
if (isset($value['options']['type'])) {
$options = ", type : '".$value['options']['type']."'";
switch($value['options']['type']) {
case 'select' : $options .= ", editoptions : { value : '" . $value['options']['edit_options'] . "' }"; break;
case 'date' :
case 'radio' :
case 'checkbox' :
default :
}
}
}
if ($value[4] == 2)
$searchitems .= "{display: '".$value[0]."', name : '".$index."', isdefault: true " .$options. "},";
else if ($value[4] == 1)
$searchitems .= "{display: '".$value[0]."', name : '".$index."' " .$options. "},";
}
}
//Remove the last ","
$grid_js = substr($grid_js,0,-1).'],';
$searchitems = substr($searchitems,0,-1).']';
//Add searchitems to grid
$grid_js .= $searchitems;
//Get buttons
if (is_array($buttons))
{
$grid_js .= ",buttons : [";
foreach ($buttons as $index => $value) {
if ($value[0] == 'separator')
$grid_js .= "{separator: true},";
else
$grid_js .= "{name: '".$value[0]."', bclass : '".$value[1]."', onpress : ".$value[2]."},";
}
//Remove the last ","
$grid_js = substr($grid_js,0,-1).']';
}
//Finalize
$grid_js .= "}); })</script>";
return $grid_js;
}
}
?>
I solve looking here: https://github.com/sameersemna/ci-flexigrid
Just download codeigniter-flexigrid project, import database and set database credentials in database.php.
This is the live example from github project:
http://ci-flexigrid.sameershemna.com/countries
I like this solution because you do not need grocery-crud library but just simply codeigniter
cheers

Google speech API - php does not return anything

My code is inspired by this php version of full duplex google speech API for speech-to-text : http://mikepultz.com/2013/07/google-speech-api-full-duplex-php-version/
I have few flac files that do work and give the array output as explained on Mike's post. But for few flac files it just doesn't return anything as output. For example : http://gavyadhar.com/video/upload/Pantry_Survey.flac, no output is returned.
But the same code works for this flac file: http://gavyadhar.com/video/upload/pantry_snack_video.flac and returns the array output as following:
---------response 1 : your face a pantry and one of the main stacks I usually Wesley Rd rasa multigrain crackers and I like them because they're pretty healthy for you and [...]
...and so on 5 responses.
Can anyone tell me, why is it that some flac files don't work? Or is there any way to catch the exceptions which are created by google API and display them to troubleshoot?
Thanks. Attaching my code here of two php files:
PHP file which passes the API key and the FLAC file with its sample rate.
<?php
include 'GoogleSpeechToText.php';
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
// Your API Key goes here.
$apiKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // my API server key
$speech = new GoogleSpeechToText($apiKey);
#var_dump($speech);
$file = realpath('upload/Pantry_Survey.flac'); // Full path to the file.
echo "<BR><BR>file : ", $file ;
#print_r("<br>-------------------");
#print_r($file1);
#print_r("<br>-------------------");
$bitRate = 44100; // The bit rate of the file.
$result = $speech->process($file, $bitRate, 'en-US');
print_r($result);
echo "<BR><BR>-------------";
$responses = $result[0]['alternative'];
$i = 0;
foreach ($responses as $response) {
$i = $i + 1;
#echo $response['transcript'];
echo "<br><br> ---------response $i : ", $response['transcript'];
}
?>
GoogleSpeechToText.php
<?php
/**
* Convert FLAC files to Text using the Google Speech API
*
* Credit due to Mike (mike#mikepultz.com) for his first version of this.
*
* #version 0.1
* #author Roger Thomas
* #see
*
*/
class GoogleSpeechToText
{
/**
* URL of the Speech API
* #var string
*/
const SPEECH_BASE_URL = 'https://www.google.com/speech-api/full-duplex/v1/';
/**
* A 'unique' string to use for the requests
*
* #var string
*/
private $requestPair;
/**
* The Google Auth API Key
*
* #var string
*/
private $apiKey;
/**
* CURL Upload Handle
*
* #var resource
*/
private $uploadHandle;
/**
* CURL Download Handle
*
* #var resource
*/
private $downloadHandle;
/**
* Construct giving the Google Auth API Key.
*
* #param string $apiKey
* #throws Exception
*/
public function __construct($apiKey)
{
if (empty($apiKey)) {
throw new Exception('$apiKey should not be empty.');
}
$this->apiKey = $apiKey;
$this->requestPair = $this->getPair();
$this->setupCurl();
}
/**
* Setup CURL requests, both up and down.
*/
private function setupCurl()
{
$this->uploadHandle = curl_init();
$this->downloadHandle = curl_init();
curl_setopt($this->downloadHandle, CURLOPT_URL, self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair );
#echo "<br>downloadHandle :: ", self::SPEECH_BASE_URL . 'down?pair=' . $this->requestPair;
curl_setopt($this->downloadHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->uploadHandle,CURLOPT_RETURNTRANSFER,true);
curl_setopt($this->uploadHandle,CURLOPT_POST,true);
//----added by asmi shah - 7 jan 2015
curl_setopt($this->uploadHandle, CURLOPT_MAX_SEND_SPEED_LARGE, 30000);
curl_setopt($this->uploadHandle, CURLOPT_LOW_SPEED_TIME, 9999);
curl_setopt($this->downloadHandle, CURLOPT_LOW_SPEED_TIME, 9999);
//----
}
/**
* Generate a Pair for the request. This identifies the requests later.
*
* #return string
*/
private function getPair()
{
$c = '0123456789';
$s = '';
for ($i=0; $i<16; $i++) {
$s .= $c[rand(0, strlen($c) - 1)];
}
echo "pair : ",$s;
return $s;
}
/**
* Make the request, returning either an array, or boolean false on
* failure.
*
* #param string $file the file name to process
* #param integer $rate the bitrate of the flac content (example: 44100)
* #param string $language the ISO language code
* (en-US has been confirmed as working)
* #throws Exception
* #return array|boolean false for failure.
*/
public function process($file, $rate, $language = 'en-US')
{
if (!$file || !file_exists($file) || !is_readable($file)) {
throw new Exception(
'$file must be specified and be a valid location.'
);
}
else { echo "<br>file exists"; }
$data = file_get_contents($file);
#var_dump($rate);
if (!$data) {
throw new Exception('Unable to read ' . $file);
}
else { echo "<br>file is readable"; }
$upload_data = array(
"Content_Type" => "audio/x-flac; rate=". $rate,
"Content" => $data,
);
if (empty($rate) || !is_integer($rate)) {
throw new Exception('$rate must be specified and be an integer');
}
else { echo "<br>sample rate is received :" . $rate ; }
curl_setopt($this->uploadHandle,CURLOPT_URL,self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&timeout=20&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey);
curl_setopt($this->uploadHandle,CURLOPT_HTTPHEADER,array('Transfer-Encoding: chunked','Content-Type: audio/x-flac; rate=' . $rate));
curl_setopt($this->uploadHandle,CURLOPT_POSTFIELDS,$upload_data);
#echo "<br><br>------ data : ", $data;
#echo "<br><br>------";
#echo "<BR><BR> URL made up : ", self::SPEECH_BASE_URL . 'up?lang=' .$language . '&lm=dictation&client=chromium&pair=' .$this->requestPair . '&key=' . $this->apiKey;
$curlMulti = curl_multi_init();
curl_multi_add_handle($curlMulti, $this->downloadHandle);
curl_multi_add_handle($curlMulti, $this->uploadHandle);
$active = null;
do {
curl_multi_exec($curlMulti, $active);
} while ($active > 0);
$res = curl_multi_getcontent($this->downloadHandle);
#var_dump($this->downloadHandle);
#echo "resource type ::".get_resource_type($this->downloadHandle);
$output = array();
$results = explode("\n", $res);
#var_dump($results);
#$i = 0;
foreach ($results as $result) {
#$i = $i + 1;
#echo "<BR><BR><BR>--------------- string ||$i|| : ", $result;
$object = json_decode($result, true);
if (
(isset($object['result']) == true) &&
(count($object['result']) > 0)
) {
foreach ($object['result'] as $obj) {
$output[] = $obj;
}
}
}
curl_multi_remove_handle($curlMulti, $this->downloadHandle);
curl_multi_remove_handle($curlMulti, $this->uploadHandle);
curl_multi_close($curlMulti);
if (empty($output)) {
echo "<BR><br>output is empty<BR>";
return false;
}
echo "<BR><BR>";
return $output;
}
/**
* Close any outstanding connections in the destruct
*/
public function __destruct()
{
curl_close($this->uploadHandle);
curl_close($this->downloadHandle);
}
}
?>
The audio file you provided uses 2 channels. As speech currently only supports single channel audio, you will need to convert it down to a single channel.
All encodings support only 1 channel (mono) audio.
Audio encoding detail of Google speech API
After converting the audio file down to 1 channel I was able to successfully get a response with the provided audio file.
For your information the SPEECH_BASE_URL = 'https://www.google.com/speech-api/full-duplex/v1/'; is now deprecated, the new one is: https://speech.googleapis.com/v1/speech:recognize?key=YOUR_API_KEY
as per https://cloud.google.com/speech/docs/auth#using_an_api_key

First Drupal Module - converting PHP script to Drupal 7 Module

I am trying to convert a much used PHP script that has served me well as a block for a while but now I am trying to convert it into a module for ease of use, and for the challenge. It puts a block into the list but not any content into the block. As I am more of a HTML5 / CSS3 geek this PHP is a little new to me. Could anyone help mentor me here? Many thanks
<code>
<?php
/**
* #file
* A block module that displays a local weather forcast for Reading Berks UK.
*/
function moduleone_help($path, $arg) {
switch ($path) {
case "admin/help#moduleone":
return '<p>' . t("Displays the weather for a user defined region defined by <a href='#'>LINK</a>") . '</p>';
break;
}
}
/**
* Implement hook_block_info().
*/
function moduleone_block_info() {
$blocks['moduleone'] = array(
// The name that will appear in the block list.
'info' => t('Module One Weather'),
// Default setting.
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Custom content function.
*
* Get weather report from Yahoo
* Output var is $output.
*
* #return
* A result set of the targeted posts.
*/
function moduleone_weather(){
$zipcode = 'UKXX0117';
$result = file_get_contents('http://weather.yahooapis.com/forecastrss?p=' . $zipcode . '&u=f');
$xml = simplexml_load_string($result);
//echo htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
$xml->registerXPathNamespace('yweather', 'http://xml.weather.yahoo.com/ns/rss/1.0');
$location = $xml->channel->xpath('yweather:location');
if(!empty($location)){
foreach($xml->channel->item as $item){
$current = $item->xpath('yweather:condition');
$forecast = $item->xpath('yweather:forecast');
$current = $current[0];
$output = <<<END
<h1 style="margin-bottom: 0">Weather for {$location[0]['city']}, {$location[0]['region']}</h1>
<small>{$current['date']}</small>
<h2>Current Conditions</h2>
<p>
<span style="font-size:72px; font-weight:bold;">{$current['temp']}°F</span>
<br/>
<img src="http://l.yimg.com/a/i/us/we/52/{$current['code']}.gif" style="vertical-align: middle;"/>
{$current['text']}
</p>
<h2>Forecast</h2>
{$forecast[0]['day']} - {$forecast[0]['text']}. High: {$forecast[0]['high']} Low: {$forecast[0]['low']}
<br/>
{$forecast[1]['day']} - {$forecast[1]['text']}. High: {$forecast[1]['high']} Low: {$forecast[1]['low']}
<br/>
{$forecast[2]['day']} - {$forecast[2]['text']}. High: {$forecast[2]['high']} Low: {$forecast[2]['low']}
</p>
END;
}
}else{
$output = 'No results found, please try a different zip code.';
}
function moduleone_block_view($delta = '') {
switch ($delta) {
case 'moduleone':
$block['subject'] = t('Weather Conditions');
if (user_access('access content')) {
}
if (empty($output)) {
$block['content'] = t('No forcast available.');
}
else {
$block['content'] = theme('item_list', array(
'items' => $output));
}
}
return $block;
}
}</code>
Drupal works via a system of hooks which you override, so rightly you've overridden hook_help, hook_block_info and hook_block_view but there is no hook_weather (well, at least not in core Drupal although a contributed module may provide one) so at the moment moduleone_weather() is never called.
You could fix this by placing $output = moduleone_weather(); before you check whether $output is empty or not in your hook_block_view function.

PHP entity class generator

I am creating entity (of entity-view-controller)(in other words, model of MVC) classes which theoreticlly match the databse table I have. Is there a tool which reads mysql table and creates a model class code? (NOT on execution, a code output is required)
I expect an output like
class{
public $columnname1;
public $columnname2;
public $columnname3;
public $columnname4;
public $columnname5;
public $columnname6;
function __construct(&$columnname1, &$columnname2){...}
function insert(&$columnname1, &$columnname2){}
function delete(&$columnname1){}
...
}
A tool which would also create insert,update and delete by id functions would help me a lot.
The tool may be free or paid.
PDO can fetch results into an object.
Design a class which matches your database/query structure, and use PDO::FETCH_INTO to fetch the result set into an already instantiated object. Misread the question, my bad.
To generate the class itself from the database structure, there are several projects (I haven't tested, but this came up on a very simple search).
db2php
PHP MySQL class generator
The following code is what I've used for a long time to create PHP models for MySQL and DB2 tables. I've got stubs in place for MSSQL, PGSQL and SQLite but have never needed to complete them.
Here's the code generator class:
<?php
/**
* #license http://opensource.org/licenses/MIT The MIT License
* #version 1.0.0_20130220000000
*/
/**
* This class will generate PHP source code for a "model" that interfaces with
* a database table.
*
* #license http://opensource.org/licenses/MIT The MIT License
* #version 1.0.0_20130220000000
*/
class db_code_generator{
private $closing_tag;
private $columns;
private $database;
private $host;
private $password;
private $port;
private $table;
private $type;
private $username;
/**
* Constructor. By default we will try to connect to a MySQL database on
* localhost.
*
* #param string $database The name of the database the user wants to connect
* to.
*
* #param string $table The name of the table to generate code for.
*
* #param string $username The username we should use to connect to the
* database.
*
* #param string $password The password we need to connect to the database.
*
* #param string $host The host or server we will try to connect to. If the
* user doesn't give us a host we default to localhost.
*
* #param string $port The port we should try to connect to. Typically this
* will not be passed so we default to NULL.
*
* #param string $type The type of database we are connecting to. Valid
* values are: db2, mssql, mysql, pgsql, sqlite.
*/
public function __construct($database = NULL,
$table = NULL,
$username = NULL,
$password = NULL,
$host = 'localhost',
$type = 'mysql',
$port = NULL,
$closing_tag = TRUE){
$this->database = $database;
$this->table = $table;
$this->username = $username;
$this->password = $password;
$this->host = $host;
$this->port = $port;
$this->type = $type;
$this->closing_tag = $closing_tag;
}
/**
* Generate the code for a model that represents a record in a table.
*
* #return string The PHP code generated for this model.
*/
public function get_code(){
$this->get_data_definition();
$code = $this->get_file_head();
$code .= $this->get_properties();
$code .= $this->get_ctor();
$code .= $this->get_dtor();
$code .= $this->get_method_stubs();
$code .= $this->get_file_foot();
return $code;
}
/**
* Create the code needed for the __construct function.
*
* #return string The PHP code for the __construct function.
*/
private function get_ctor(){
$code = "\t/**\n";
$code .= "\t * Constructor.\n";
$code .= "\t *\n";
$code .= "\t * #param mixed \$id The unique id for a record in this table. Defaults to NULL\n";
if ('db2' === $this->type){
$code .= "\n\t * #param string \$library The library where the physical file resides. Defaults to LIBRARY\n";
}
$code .= "\t *\n";
$code .= "\t * #see base_$this->type::__construct\n";
$code .= "\t */\n";
if ('db2' === $this->type){
$code .= "\tpublic function __construct(\$id = NULL, \$library = 'LIBRARY'){\n";
$code .= "\t\tparent::__construct(\$id, \$library);\n";
}else{
$code .= "\tpublic function __construct(\$id = NULL){\n";
$code .= "\t\tparent::__construct(\$id);\n";
}
$code .= "\t}\n\n";
return $code;
}
/**
* Connect to the requested database and get the data definition for the
* requested table.
*/
private function get_data_definition(){
try{
switch ($this->type){
case 'db2':
$this->get_data_definition_db2();
break;
case 'mssql':
$this->get_data_definition_mssql();
break;
case 'mysql':
$this->get_data_definition_mysql();
break;
case 'pgsql':
$this->get_data_definition_pgsql();
break;
case 'sqlite':
$this->get_data_definition_sqlite();
break;
}
}catch(PDOException $e){
}
}
/**
* Get data definition information for a DB2 table.
*/
private function get_data_definition_db2(){
$con = new PDO("odbc:DRIVER={iSeries Access ODBC Driver};SYSTEM=$this->host;PROTOCOL=TCPIP", $this->username, $this->password);
$sql = "SELECT COLUMN_NAME, COLUMN_SIZE, COLUMN_TEXT, DECIMAL_DIGITS, ORDINAL_POSITION, TYPE_NAME FROM SYSIBM.SQLCOLUMNS WHERE TABLE_SCHEM = '". strtoupper($this->database) ."' AND TABLE_NAME = '". strtoupper($this->table) ."'";
$statement = $con->prepare($sql);
if ($statement->execute()){
while ($row = $statement->fetch()){
if (NULL !== $row['DECIMAL_DIGITS']){
$decimal = $row['DECIMAL_DIGITS'];
}else{
$decimal = NULL;
}
if ('DECIMAL' === $row['TYPE_NAME'] && NULL !== $row['DECIMAL_DIGITS'] && '0' !== $row['DECIMAL_DIGITS']){
$type = 'float';
}else if ('DECIMAL' === $row['TYPE_NAME']){
$type = 'integer';
}else{
$type = strtolower($row['TYPE_NAME']);
}
if ('1' === $row['ORDINAL_POSITION']){
$key = 'PRI';
}else{
$key = NULL;
}
$this->columns[$row['COLUMN_NAME']] = array('allow_null' => TRUE,
'decimal' => $decimal,
'default' => NULL,
'extra' => NULL,
'key' => $key,
'length' => $row['COLUMN_SIZE'],
'name' => $row['COLUMN_NAME'],
'text' => $row['COLUMN_TEXT'],
'type' => $type);
}
ksort($this->columns);
}
}
/**
* Get data definition information for a MS SQL table.
*/
private function get_data_definition_mssql(){
return "The code for generating MS SQL models is not yet implemented.\n";
}
/**
* Get data definition information for a MySQL table.
*/
private function get_data_definition_mysql(){
$dsn = "mysql:host=$this->host;";
if (NULL !== $this->port){
$dsn .= "port=$this->port;";
}
$dsn .= "dbname=$this->database";
$con = new PDO($dsn, $this->username, $this->password);
$sql = "SHOW COLUMNS FROM $this->table";
$statement = $con->prepare($sql);
if ($statement->execute()){
while ($row = $statement->fetch()){
$this->columns[$row['Field']] = array('allow_null' => $row['Null'],
'decimal' => NULL,
'default' => $row['Default'],
'extra' => $row['Extra'],
'key' => $row['Key'],
'length' => NULL,
'name' => $row['Field'],
'text' => NULL,
'type' => $row['Type']);
}
ksort($this->columns);
}
}
/**
* Get data definition information for a PostgreSQL table.
*/
private function get_data_definition_pgsql(){
return "The code for generating PostgreSQL models is not yet implemented.\n";
}
/**
* Get data definition information for a SQLite table.
*/
private function get_data_definition_sqlite(){
return "The code for generating SQLite models is not yet implemented.\n";
}
/**
* Create the code needed for the __destruct function.
*
* #return string The PHP code for the __destruct function.
*/
private function get_dtor(){
$code = "\t/**\n";
$code .= "\t * Destructor.\n";
$code .= "\t */\n";
$code .= "\tpublic function __destruct(){\n";
$code .= "\t\tparent::__destruct();\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code found at the end of the file - the closing brace, the
* ending PHP tag and a new line. Some PHP programmers prefer to not have a
* closing PHP tag while others want the closing tag and trailing newline -
* it probably just depends on their programming background. Regardless it's
* best to let everyone have things the way they want.
*/
private function get_file_foot(){
$code = '';
if ($this->closing_tag){
$code .= "}\n?>\n";
}else{
$code .= '}';
}
return $code;
}
/**
* Generate the code found at the beginning of the file - the PHPDocumentor
* doc block, the require_once for the correct base class and the class name.
*
* #return string The code generated for the beginning of the file.
*/
private function get_file_head(){
$code = "<?php\n";
$code .= "/**\n";
$code .= " * Please enter a description of this class.\n";
$code .= " *\n";
$code .= " * #author XXX <XXX#domain.com>\n";
$code .= " * #copyright Copyright (c) ". date('Y') ."\n";
$code .= " * #license http://www.gnu.org/licenses/gpl-3.0.html GPLv3\n";
$code .= " * #version ". date('Ymd') ."\n";
$code .= " */\n\n";
$code .= "require_once('base_$this->type.php');\n\n";
$code .= "class ". strtolower($this->table) ." extends base_$this->type{\n";
return $code;
}
/**
* Generate the code for a delete method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_delete(){
$code = "\t/**\n";
$code .= "\t * Override the delete method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param mixed \$id The unique record ID to be deleted.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully deleted from the table, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function delete(\$id){\n";
$code .= "\t\treturn parent::delete(\$id);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code for an insert method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_insert(){
$code = "\t/**\n";
$code .= "\t * Override the insert method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param array \$parms An array of data, probably the \$_POST array.\n";
$code .= "\t * #param bool \$get_insert_id A flag indicating if we should get the autoincrement value of the record just created.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully inserted into the table, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function insert(\$parms, \$get_insert_id = FALSE){\n";
$code .= "\t\treturn parent::insert(\$parms, \$get_insert_id);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Generate the code for an update method stub.
*
* #return string The PHP code for the method stub.
*/
private function get_method_stub_update(){
$code = "\t/**\n";
$code .= "\t * Override the update method found in the base class.\n";
$code .= "\t *\n";
$code .= "\t * #param array &\$parms An array of key=>value pairs - most likely the \$_POST array.\n";
$code .= "\t *\n";
$code .= "\t * #param integer \$limit The number of records to update. Defaults to NULL.\n";
$code .= "\t *\n";
$code .= "\t * #return bool TRUE if a record was successfully updated, FALSE otherwise.\n";
$code .= "\t */\n";
$code .= "\tpublic function update(\$parms, \$limit = NULL){\n";
$code .= "\t\treturn parent::update(\$parms, \$limit);\n";
$code .= "\t}\n\n";
return $code;
}
/**
* Create method stubs for create, delete and update.
*
* #return string The PHP code for these stubs.
*/
private function get_method_stubs(){
$code = $this->get_method_stub_delete();
$code .= $this->get_method_stub_insert();
$code .= $this->get_method_stub_update();
return $code;
}
private function get_properties(){
$code = '';
if (count($this->columns)){
foreach ($this->columns AS $index => $col){
$code .= "\t/**\n";
if (NULL !== $col['text']){
$code .= "\t * $col[text]\n";
}else{
$code .= "\t * Description\n";
}
$code .= "\t * #var ". $col['type'];
if (NULL !== $col['length']){
$code .= " ($col[length]";
if (NULL !== $col['decimal']){
$code .= ",$col[decimal]";
}
$code .= ")";
}
$code .= "\n\t */\n";
$temp_name = str_replace('#', '_', $col['name']);
$code .= "\tpublic \$$temp_name;\n\n";
}
}
return $code;
}
}
?>
and here's a simple page to use it:
<?php
/**
* #license GPLv3 (http://www.gnu.org/licenses/gpl-3.0.html)
* #version 1.0.0_20130220000000
*/
require_once('db_code_generator.php');
$table_type = array();
$table_type['db2'] = 'DB2/400 (db2)';
$table_type['mssql'] = 'Microsoft SQL Server (mssql)';
$table_type['mysql'] = 'MySQL (mysql)';
$table_type['pgsql'] = 'PostGRESQL (pgsql)';
$table_type['sqlite'] = 'SQLite (sqlite)';
$database = (isset($_POST['database'])) ? $_POST['database'] : 'my_database';
$host = (isset($_POST['host'])) ? $_POST['host'] : 'localhost';
$username = (isset($_POST['username'])) ? $_POST['username'] : 'root';
$password = (isset($_POST['password'])) ? $_POST['password'] : '';
$table = (isset($_POST['table'])) ? $_POST['table'] : '';
$type = (isset($_POST['type'])) ? $_POST['type'] : 'mysql';
$library = (isset($_POST['library'])) ? $_POST['library'] : 'LIBRARY';
$file = (isset($_POST['file'])) ? $_POST['file'] : 'STATES';
//---------------------------------------------------------------------------
?>
<div class="data_input">
<form action="" method="post">
<fieldset class="top">
<legend>Code Generator</legend>
<label for="host">Hostname or IP:
<input id="host" maxlength="32" name="host" tabindex="<?php echo $tabindex++; ?>" title="Enter the database host name" type="text" value="<?php echo $host; ?>" />
</label>
<br />
<label for="username">Username:
<input id="username" maxlength="32" name="username" tabindex="<?php echo $tabindex++; ?>" title="Enter the database username" type="text" value="<?php echo $username; ?>" />
</label>
<br />
<label for="password">Password:
<input id="password" maxlength="32" name="password" tabindex="<?php echo $tabindex++; ?>" title="Enter the database password" type="password" value="<?php echo $password; ?>" />
</label>
<br />
<label for="type">Type:
<select id="type" name="type" tabindex="<?php echo $tabindex++; ?>">
<?php
foreach ($table_type AS $key=>$value){
echo('<option ');
if ($key == $type){
echo 'selected="selected" ';
}
echo 'value="'. $key .'">'. $value .'</option>';
}
?>
</select>
</label>
<br />
</fieldset>
<fieldset class="top">
<legend>PostGRESQL/MSSQL/MySQL Parameters</legend>
<label for="database">Database:
<input id="database" maxlength="100" name="database" tabindex="<?php echo $tabindex++; ?>" title="Enter the database name" type="text" value="<?php echo $database; ?>" />
</label>
<br />
<label for="table">Table:
<input id="table" maxlength="100" name="table" tabindex="<?php echo $tabindex++; ?>" title="Enter the table name" type="text" value="<?php echo $table; ?>" />
</label>
<br />
</fieldset>
<fieldset class="top">
<legend>DB2 Parameters</legend>
<label for="library">Library:
<input id="library" maxlength="10" name="library" tabindex="<?php echo $tabindex++; ?>" title="Enter the library name" type="text" value="<?php echo $library; ?>" />
</label>
<br />
<label for="file">Physical File:
<input id="file" maxlength="10" name="file" tabindex="<?php echo $tabindex++; ?>" title="Enter the file name" type="text" value="<?php echo $file; ?>" />
</label>
<br />
</fieldset>
<fieldset class="bottom">
<button tabindex="<?php echo $tabindex++; ?>" type="submit">Generate!</button>
</fieldset>
</form>
</div>
<?php
if (isset($_POST['host'])){
if ('db2' == $_POST['type']){
$_POST['database'] = strtoupper($_POST['library']); // Library
$_POST['table'] = strtoupper($_POST['file']); // Physical file
$_POST['host'] = 'db2_host';
$_POST['username'] = 'db2_username';
$_POST['password'] = 'db2_password';
}
$object = new db_code_generator($_POST['database'], $_POST['table'], $_POST['username'], $_POST['password'], $_POST['host'], $_POST['type']);
echo('<textarea rows="75" style="margin-left : 50px; width : 90%;" onfocus="select()">'. $object->get_code() .'</textarea>');
}
?>
I understand you're looking for a ORM kind of a thing.
hope this helps
http://www.doctrine-project.org/
http://propelorm.org/
What about symfony? It does exactly what you say and you get a beastly good framework to go with it.
symfony 'compiles' classes for you based on a data model that you supply. It will make sure that compiled classes and MySQL database structure are in sync.
This approach is favorable over a Reflection based approach as it's simply too slow.
For what it's worth, Rafael Rocha shares code here.
Still, I strongly propose to use an ORM. Transforming MySQL structure back to a database-abstraction layer is anything but good...
Try this
https://github.com/rcarvello/mysqlreflection
A useful utility I built for the Object Relation Mapping of MySQL databases.
The utility generates automatically PHP classes for any tables of a given database schema.
The package is extracted from my personal PHP Web MVC Framework.
Yes, Doctrine is what you need.
Run a command, and you get all your tables' metadata in XML or YML format(choice is yours)
$ php app/console doctrine:mapping:convert xml ./src/Bundle/Resources/config/doctrine/metadata/orm --from-database --force
Once you generate the Metadata, command Doctrine to import the schema to build related entity classes you need. You will find all GET and SET functionality(read SELECT, UPDATE and INSERT) inside.
1.$ php app/console doctrine:mapping:import Bundle annotation
2.$ php app/console doctrine:generate:entities Bundle
Read details with Example here
Fat free framework allows you to work with existing tables using code like:
$user=new DB\SQL\Mapper($db,'users');
// or $user=new DB\Mongo\Mapper($db,'users');
// or $user=new DB\Jig\Mapper($db,'users');
$user->userID='jane';
$user->password=md5('secret');
$user->visits=0;
$user->save();
The code above creates new record in users table
I have written a PHP code which will automatically detect all the databases in MYSQL database, on selecting any of the database all of its related tables are loaded. You can select all the tables or any respective table to generate the Modal Class.
The following is the link to my repository
https://github.com/channaveer/EntityGenerator
This will automatically create Entity folder and dump all the entity class into that folder.
NOTE - Currently only supported for MYSQL
Hope it helps. Happy Coding!
I think you should make itout on your on. Every project and requirement of Model Code is different in my opinion. Two mysql queries will keep you in ease.
SHOW TABLES FROM db_NAME //this gives the table listing, so its Master Looper
DESC tbl_name //detail query that fetches column information of given table
DESC tbl_name will give Field, Type, Null, Key, Default and Extra Columns.
e.g. values seperated in pipes (|):
Id | int(11) | NO | PRI | NULL | auto_increment |
I followed these to make Model, controller and Viewer files supporting CRUD operation in Codeigniter 2 way back. It worked just fine.

PHP pagination - problem displaying correct content on additional pages

I found this awesome code online to help with pagination, and it's working well, the only problem is: each page displays the same 4 rows.
Any ideas will be much appreciated
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
$a=0;
while ($a < $num) {
$id=mysql_result($result,$a,"id");
$title=mysql_result($result,$a,"title");
$strategies=mysql_result($result,$a,"strategies");
$client=mysql_result($result,$a,"client");
$copy=mysql_result($result,$a,"copy");
$thumbmedia=mysql_result($result,$a,"thumbmedia");
$niche=mysql_result($result,$a,"niche");
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
$a++;
}
}
//Display the navigation
echo $pager->renderNav();
?>
This is the included file:
<?php
/**
* PHPSense Pagination Class
*
* PHP tutorials and scripts
*
* #package PHPSense
* #author Jatinder Singh Thind
* #copyright Copyright (c) 2006, Jatinder Singh Thind
* #link http://www.phpsense.com
*/
// ------------------------------------------------------------------------
class PS_Pagination {
var $php_self;
var $rows_per_page; //Number of records to display per page
var $total_rows; //Total number of rows returned by the query
var $links_per_page; //Number of links to display per page
var $sql;
var $debug = false;
var $conn;
var $page;
var $max_pages;
var $offset;
/**
* Constructor
*
* #param resource $connection Mysql connection link
* #param string $sql SQL query to paginate. Example : SELECT * FROM users
* #param integer $rows_per_page Number of records to display per page. Defaults to 10
* #param integer $links_per_page Number of links to display per page. Defaults to 5
*/
function PS_Pagination($connection, $sql, $rows_per_page = 1, $links_per_page = 5) {
$this->conn = $connection;
$this->sql = $sql;
$this->rows_per_page = $rows_per_page;
$this->links_per_page = $links_per_page;
$this->php_self = htmlspecialchars($_SERVER['PHP_SELF']);
if(isset($_GET['page'])) {
$this->page = intval($_GET['page']);
}
}
/**
* Executes the SQL query and initializes internal variables
*
* #access public
* #return resource
*/
function paginate() {
if(!$this->conn) {
if($this->debug) echo "MySQL connection missing<br />";
return false;
}
$all_rs = #mysql_query($this->sql);
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_num_rows($all_rs);
#mysql_close($all_rs);
$this->max_pages = ceil($this->total_rows/$this->rows_per_page);
//Check the page value just in case someone is trying to input an aribitrary value
if($this->page > $this->max_pages || $this->page <= 0) {
$this->page = 1;
}
//Calculate Offset
$this->offset = $this->rows_per_page * ($this->page-1);
//Fetch the required result set
$rs = #mysql_query($this->sql." LIMIT {$this->offset}, {$this->rows_per_page}");
if(!$rs) {
if($this->debug) echo "Pagination query failed. Check your query.<br />";
return false;
}
return $rs;
}
/**
* Display the link to the first page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'First'
* #return string
*/
function renderFirst($tag='First') {
if($this->page == 1) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the link to the last page
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to 'Last'
* #return string
*/
function renderLast($tag='Last') {
if($this->page == $this->max_pages) {
return $tag;
}
else {
return ''.$tag.'';
}
}
/**
* Display the next link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '>>'
* #return string
*/
function renderNext($tag=' >>') {
if($this->page < $this->max_pages) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the previous link
*
* #access public
* #param string $tag Text string to be displayed as the link. Defaults to '<<'
* #return string
*/
function renderPrev($tag='<<') {
if($this->page > 1) {
return ''.$tag.'';
}
else {
return $tag;
}
}
/**
* Display the page links
*
* #access public
* #return string
*/
function renderNav() {
for($i=1;$i<=$this->max_pages;$i+=$this->links_per_page) {
if($this->page >= $i) {
$start = $i;
}
}
if($this->max_pages > $this->links_per_page) {
$end = $start+$this->links_per_page;
if($end > $this->max_pages) $end = $this->max_pages+1;
}
else {
$end = $this->max_pages;
}
$links = '';
$niche = $_GET['niche'];
for( $i=$start ; $i<$end ; $i++) {
if($i == $this->page) {
$links .= " $i ";
}
else {
$links .= ' '.$i.' ';
}
}
return $links;
}
/**
* Display full pagination navigation
*
* #access public
* #return string
*/
function renderFullNav() {
return $this->renderFirst().' '.$this->renderPrev().' '.$this->renderNav().' '.$this->renderNext().' '.$this->renderLast();
}
/**
* Set debug mode
*
* #access public
* #param bool $debug Set to TRUE to enable debug messages
* #return void
*/
function setDebug($debug) {
$this->debug = $debug;
}
}
?>
Just at first glance i see your query is repeating itself from the beginning every time you run it, so that means every time you run it it searches from the beggining. you need a counter to tell it where to start from on the next page. something like:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}' limit $startPoint, $offset";
that way the offset is the same as the number of items you want per page and the $startPoint is the point at which the search beggins at the next iteration.
somehting like this would work:
if(!$startPoint){$startPoint = 0;}else{$startPoint = {$_GET['$startPoint'];}
within your code pass the start point back to the query and increasing it by the offset after each iteration.
Please bear in mind i've not taking into consideration stuff like injection, and the fact that the variable $num doesn't seem to come from anywhere in the 1st file. I cant see where you initialized it so as to test $a against it.
After looking at your code more in depth i found a few things that need to be changed to get it work in the least here is the changed code:
<?php
//Include the PS_Pagination class
include('includes/ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect("localhost", "root", "root");
mysql_select_db('database',$conn);
$sql = "SELECT * FROM studies";// WHERE niche = '{$_GET['niche']}'";
//Create a PS_Pagination object
$pager = new PS_Pagination($conn,$sql,4,5);
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
// $a=0;
// while ($a < $num) {
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
$id=$row['id'];
$title=$row['title'];
$strategies=$row['strategies'];
$client=$row['client'];
$copy=$row['copy'];
$thumbmedia=$row['thumbmedia'];
$niche=$row['niche'];
echo '<div class="container"><p class="subheadred">'.$title.'</p></div>';
echo '<div class="containerstudy"><div class="column1"><p class="subheadsmall">Strategies</p><p class="sidebarred">'.$strategies.'</p>';
echo '<p class="subheadsmall">Client</p><p class="sidebargrey">'.$client.'</p></div>';
echo '<div class="column2"><p class="bodygrey">'.substr($copy, 0, 300).'...more</p></div>';
echo '<div class="column3"><img src="images/'.$thumbmedia.'" height="160" /></div></div>';
// $a++;
// }
}
//Display the navigation
echo $pager->renderNav();
?>
Notice i have commented out some part that where not necessary
the variable $a was meaningless as it compared to $num which doesn't exist therefore nothing would show. Now these lines:
// $id=mysql_result($result,$a,"id");
// $title=mysql_result($result,$a,"title");
// $strategies=mysql_result($result,$a,"strategies");
// $client=mysql_result($result,$a,"client");
// $copy=mysql_result($result,$a,"copy");
// $thumbmedia=mysql_result($result,$a,"thumbmedia");
// $niche=mysql_result($result,$a,"niche");
where also wrong as you are trying to get the result set from $result. at no place had you put the result set into $result the class you have imported does that and puts the result set into an identifier called $rs.
Since you are using $row = mysql_fetch_assoc($rs) to read through the result set then to get the variables all you need to do is get the column row through an array like this
$id=$row['id'];
and so on. once you do that then the code should work as expected. However this brings us back to this:
$sql = "SELECT * FROM studies WHERE niche = '{$_GET['niche']}'";
i had to get the last part out in that this variable is not getting passed back into the query string (seeing you are using get), the other problem is the 1st time you load the page this variable 'niche' doesn't exist so the 1st time you run the code you will get a blank page, unless this script is accessed through a link that passes in this variable. at this point i have left it commented out as am not sure what you were trying to do through niche.
Hope that helps.
Do you have page set in your query string?
I think that if you changed the paginate function, so that it would have one parameter $page and you would set $this->page = $page at the begining of the function, it would work.
You would also have to change the calling of this function in your code to $pager->paginate($_GET['page']).
The pager is also very inefficient, it gets the whole query just to find out, how many rows does the response have. I would use something like:
$all_rs = #mysql_query('SELECT COUNT(*) FROM (' . $this->sql . ')');
if(!$all_rs) {
if($this->debug) echo "SQL query failed. Check your query.<br />";
return false;
}
$this->total_rows = mysql_result($all_rs, 0, 0);
#mysql_close($all_rs);
I'm not sure what this pagination library does with the index of the rows, but you are always setting $a to 0. Perhaps the index is not relative to the page but to the overall recordset being returned?
In other words, what if you set $a to 0 on page 1, 4 on page 2, etc.
You should be able to use $rows_per_page and $page to calculate it. Or perhaps that is the $offset value, so that you set $a to offset and loop it until you hit $rows_per_page additional rows.
Edit clarifying solution:
So what I see you could do is:
$a=0;
while ($a < $pager->rows_per_page) {
$row = $a + $pager->offset;
$id=mysql_result($result,$row,"id");
$title=mysql_result($result,$row,"title");
$strategies=mysql_result($result,$row,"strategies");
$client=mysql_result($result,$row,"client");
$copy=mysql_result($result,$row,"copy");
$thumbmedia=mysql_result($result,$row,"thumbmedia");
$niche=mysql_result($result,$row,"niche");
...
$a++;
}

Categories