consider we have a database with lots of people's details.
I want to filter that result buy available data.
if the table structure is like following,
How to display only results from user with country "India".
It will be possible by accessing object attributes, but I want to add this feature to the following script.
I am not an expert and this script seems to be so difficult for me to understand.
Pagination.php
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
I just want to filter the result.
Full script link https://phppot.com/php/how-to-add-pagination-in-php-with-mysql/
If possible, please add an option to filter the result by an animal name (Common Name), for example "Lion".
Update, here is the working code
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
Found solution
<?php
namespace Phppot;
use Phppot\DataSource;
class Pagination
{
private $ds;
function __construct()
{
require_once __DIR__ . './../lib/DataSource.php';
$this->ds = new DataSource();
}
public function getPage()
{
// adding limits to select query
require_once __DIR__ . './../Common/Config.php';
$limit = Config::LIMIT_PER_PAGE;
// Look for a GET variable page if not found default is 1.
if (isset($_GET["page"])) {
$pn = $_GET["page"];
} else {
$pn = 1;
}
$startFrom = ($pn - 1) * $limit;
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion LIMIT ? , ?';
$paramType = 'ii';
$paramValue = array(
$startFrom,
$limit
);
$result = $this->ds->select($query, $paramType, $paramValue);
return $result;
}
public function getAllRecords()
{
$query = 'SELECT * FROM tbl_animal WHERE common_name=Lion';
$totalRecords = $this->ds->getRecordCount($query);
return $totalRecords;
}
}
?>
Related
I'm moving an older PHP script over to mysqli queries, I'm having trouble with mysqli_real_escape_string in validation code for signups.
PHP message: PHP Notice: Undefined variable: link in
/srv/www/public_html/classes/validation.class.php on line 38
PHP message: PHP Warning: mysqli_real_escape_string() expects
parameter 1 to be mysqli, null given in
/srv/www/public_html/classes/validation.class.php on line 38" while
reading response header from upstream
validation.class.php as follows;
<?php
defined('_VALID') or die('Restricted Access!');
class VValidation
{
public function username($username)
{
if (!preg_match('/^[a-zA-Z0-9_]*$/', $username)) {
return false;
} elseif (preg_match('/^[_]*$/', $username)) {
return false;
}
$users_blocked = array(
'edit',
'prefs',
'blocks',
'delete',
'avatar'
);
if (in_array($username, $users_blocked)) {
return false;
}
return true;
}
public function usernameExists($username) {
global $conn;
$sql = "SELECT UID FROM signup WHERE username = '" . mysqli_real_escape_string($username) . "' LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
public function email($email)
{
// First, we check that there's one # symbol, and that the lengths are right
if (!preg_match("/^[^#]{1,64}#[^#]{1,255}$/", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of # symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("#", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
return false;
}
}
if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
return false;
}
}
}
return true;
}
public function emailExists($email, $uid = NULL) {
global $conn;
$sql_add = (isset($uid)) ? " AND UID != " . intval($uid) : NULL;
$sql = "SELECT UID FROM signup WHERE email = '" . mysql_real_escape_string($email) . "'" . $sql_add . " LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
public function date($month, $day, $year) {
return checkdate($month, $day, $year);
}
public function age($month, $day, $year, $years)
{
$age = mktime(0, 0, 0, $month, $day, $year);
$real_age = mktime(0, 0, 0, date('m'), date('d'), (date('Y') - $years));
if ($age <= $real_age) {
return true;
}
return false;
}
public function zip($code, $country = 'US') {
if (!ctype_digit($code)) {
return false;
}
$length = VString::strlen($code);
switch ($country) {
case 'UK':
case 'CA':
if ($length <> 6) {
return true;
}
default:
if ($length >= 5 && $lenght <= 9) {
return true;
}
}
return false;
}
public function ip($ip)
{
if (!ip2long($ip)) {
return false;
}
}
}
?>
I've wrongly(?) assumed I can include my config to get database details;
<?php
defined('_VALID') or die('Restricted Access!');
require_once $config['BASE_DIR']. '/include/config.php';
and $link mysqli_real_escape_string
$sql = "SELECT UID FROM signup WHERE username = '" .mysqli_real_escape_string($link, $username). "' LIMIT 1";
But this provides the above errors. The include to config.php contains includes to other configs to bring it all together.
<?php
defined('_VALID') or die('Restricted Access!');
require 'config.db.php';
require $config['BASE_DIR']. '/include/dbconn.php';
$link = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
$config['db_pass'], $config['db_name']);
if ( !defined('_CONSOLE') ) {
require $config['BASE_DIR']. '/include/sessions.php';
}
disableRegisterGlobals();
... more unreleated functions
config.db.php
<?php
defined('_VALID') or die('Restricted Access!');
$config['db_type'] = 'mysqli';
$config['db_host'] = 'localhost';
$config['db_user'] = 'user1';
$config['db_pass'] = 'abc123';
$config['db_name'] = 'newdatabase';
?>
db.conn.php
<?php
defined('_VALID') or die('Restricted Access!');
$conn = ADONewConnection($config['db_type']);
if ( !$conn->Connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']) ) {
echo 'Could not connect to mysql! Please check your database settings!';
die();
}
$conn->execute("SET NAMES 'utf8'");
?>
Am I going about this the right way? Thanks for any info.
public function usernameExists($username )
{
global $conn, $config;
$link = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
$sql="SELECT UID FROM signup WHERE username = '" .mysqli_real_escape_string($link, $username). "' LIMIT 1";
$conn->execute($sql);
return $conn->Affected_Rows();
}
So I've been stuck on this for quite a while, surprisingly the update and delete functions work just fine, however I cannot make the CREATE function work properly. Please have a look at it and tell me what I'm doing wrong
<-------------- Entire model for admin panel-------------->>>>>>>> Connection to DB is working fine---------->>>>>>>>>>>
<?php
include_once "Model.php";
class ModelPages extends Model {
public function get($key) {
$sql = "SELECT * from pages where page_key = '$key'";
$row = '';
$page = Null;
foreach ($this->pdo->query($sql) as $row) {
$page = $row;
}
// echo "<pre>";
// var_dump($page);
// exit;
return $page;
}
public function getAll() {
$statement = $this->pdo->prepare("SELECT * from pages Where Id > 3");
$result = $statement->execute();
$pages = array();
if($result) {
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
}
return $pages;
}
public function updatePage($params=array()) {
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$pageId = isset($params['page_key']) ? $params['page_key'] : null;
$pageTitle = isset($params['page_title']) ? $params['page_title'] : null;
$pageBody = isset($params['page_body']) ? $params['page_body'] : null;
if ($pageId == null) {
return 'No page id provided';
}
$sql = "UPDATE " . $tableName . " SET
title = :title,
body = :body
WHERE page_key = :page_key";
$statement = $this->pdo->prepare($sql);
$statement->bindParam(':title', $pageTitle, PDO::PARAM_STR);
$statement->bindParam(':body', $pageBody, PDO::PARAM_STR);
$statement->bindParam(':page_key', $pageId, PDO::PARAM_INT);
$result = $statement->execute();
return $result;
}
public function deletePage($pageId) {
// build sql
$sql = "DELETE FROM pages WHERE id = " . intval($pageId);
$statement = $this->pdo->prepare($sql);
$result = $statement->execute();
return $result;
}
public function createPage($params=array()){
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$page_key = isset($params['page_key']) ? $params['page_key'] : 'page_key';
$pageTitle = isset($params['page_title']) ? $params['page_title'] : 'page_title';
$pageBody = isset($params['page_body']) ? $params['page_body'] : 'page_body';
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
// prepare query for execution
$statement = $this->pdo->prepare($sql);
// bind the parameters
$statement->bindParam(':page_key', $_POST['page_key']);
$statement->bindParam(':title', $_POST['title']);
$statement->bindParam(':body', $_POST['body']);
// specify when this record was inserted to the database
// Execute the query
$result = $statement->execute();
return $result;
}
}
<?php
include 'controllers/controller.php';
include 'models/Model.php';
include 'models/ModelPages.php';
<------------------------ADMIN CONTROller----------------------->>>>>>>>>>>>
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
// TODO: update DB
$tableData['page_body'] = $_POST['body'];
$tableData['table'] = 'pages';
$tableData['page_title'] = $_POST['title'];
$tableData['page_key'] = $_POST['page_key'];
$response = $ModelPages->updatePage($tableData);
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&success=true");
}
}
if(isset($_GET['page_key'])) {
// by default we assume that the key_page exists in db
$error = false;
$page = $ModelPages->get($_REQUEST['page_key']);
// if page key does not exist set error to true
if($page === null) {
$error = true;
}
// prepare data for the template
$data = $page;
$data["error"] = $error;
// display
echo $this->render2(array(), 'header.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2($data, 'admin_update_page.php');
echo $this->render2(array(), 'footer.php');
} else {
// case: delete_page
if(isset($_GET['delete_page'])) {
$response = $ModelPages->deletePage($_GET['delete_page']);
if($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&deleted=true");
}
}
}
//Get table name and make connection
if(isset($_POST['submit'])) {
$page_key = $_POST['page_key'];
$page_title = $_POST['title'];
$page_body = $_POST['body'];
$response = $ModelPages->createPage();
if($response=TRUE){
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&created=true");
}
}
}
// load all pages from DB
$pages = $ModelPages -> getAll();
// display
echo $this->render2(array(), 'header_admin.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2(array("pages"=> $pages), 'admin_view.php');
echo $this->render2(array(), 'footer.php');
}
}
?>
Since you have if(isset($_POST['page_key']) on the top:
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
...
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?
}
and it is used to call $response = $ModelPages->updatePage($tableData);
your code never reach the part with good values at the bottom:
if(!isset($_POST['page_key'])) {
...
$response = $ModelPages->createPage($tableData);
So my simple but not the best suggestion is use extra parameter when POST like action. so you can check:
if(isset($_POST['action']) && $_POST['action']=='update') {
...
} elseif (isset($_POST['action']) && $_POST['action']=='create') {
...
} etc...
hope this will help you for now :-)
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
$tablename is not in scope when the statement above is executed. And you've got no error handling in the code.
I have created joomla pagination for my own component and its working fine for joomla 2.5 and i have use same for joomla 3.0 the data is displaying and also the pagination is also displaying correctly but the issue is when i click on any pagination no. for going next or prev page its not working form remains on same page.
Here is code i have used for creating pagination.
model.php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
class eventsModelEvents extends JModelLegacy {
var $_total = null;
var $_pagination = null;
function __construct()
{
parent::__construct();
$mainframe = JFactory::getApplication();
// Get pagination request variables
$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function getPagination()
{
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
function getTotal()
{
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getData()
{
// if data hasn't already been obtained, load it
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
function _buildQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
// From the hello table
$query->from('#__events');
$query->order('date DESC');
return $query;
}
function getEvents(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__events');
$events = $db->loadObjectList();
if ($events === null)
JError::raiseError(500, 'Error reading db');
return $events;
}
function getEvent($id){
$query = ' SELECT * FROM #__events '.
' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$event = $db->loadObject();
if ($event === null)
JError::raiseError(500, 'Event with ID: '.$id.' not found.');
else
return $event;
}
function saveEvent($event){
$db = $this->getDBO();
$uploaded_path = JPATH_COMPONENT. "/images/";
if($_FILES["event_image"]["tmp_name"]){
if ($_FILES["event_image"]["error"] > 0){
return $_FILES["event_image"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["event_image"]["tmp_name"],$uploaded_path . $_FILES["event_image"]["name"]);
$event['event_image'] = $_FILES["event_image"]["name"];
}
} else {
$event['event_image'] = $event['event_stored_image'];
}
$event['event_date'] = date('Y-m-d H:i:s', strtotime($event['event_date']));
foreach($event as $key => $value){
$event[$key] = mysql_real_escape_string($value);
}
if(($event['event_name'] != NULL ) && ($event['event_image'] != NULL) && ($event['event_date'] != NULL) && ($event['event_description'] != NULL)){
if(isset($event['event_id'])){
$query = "UPDATE #__events SET name = '".$event['event_name']."',status = '".$event['event_status']."',image = '".$event['event_image']."',date = '".$event['event_date']."',description = '".$event['event_description']."',reservation = '".$event['event_reservation']."' WHERE id =" . $event['event_id'];
} else {
$query = "INSERT INTO #__events (name,status,image,date,description,reservation) VALUES ('".$event['event_name']."','".$event['event_status']."','".$event['event_image']."','".$event['event_date']."','".$event['event_description']."', '".$event['event_reservation']."')";
}
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error inserting event: '.$errorMessage);
}
} else {
return "Please Fill All fields.";
}
}
function deleteEvents($arrayIDs)
{
$query = "DELETE FROM #__events WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting events: '.$errorMessage);
}
}
function publishEvents($arrayIDs)
{
$query = "UPDATE #__events SET status = '1' WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error publishing events: '.$errorMessage);
}
}
function unpublishEvents($arrayIDs)
{
$query = "UPDATE #__events SET status = '0' WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error publishing events: '.$errorMessage);
}
}
}
view.html.php
jimport( 'joomla.application.component.view');
class eventsViewEvents extends JViewLegacy {
protected $categories;
protected $items;
protected $pagination;
protected $state;
function display($tpl = null)
{
$this->categories = $this->get('CategoryOrders');
$this->state = $this->get('State');
$this->addToolBar();
// Get data from the model
$events = $this->get('Data');
$pagination =$this->get('Pagination');
// push data into the template
$this->events = $events;
$this->assignRef('pagination', $pagination);
parent::display($tpl);
}
function add($tpl = null){
$this->addToolBar();
parent::display($tpl);
}
protected function addToolbar()
{
require_once JPATH_COMPONENT . '/helpers/events.php';
$canDo = EventsHelper::getActions($this->state->get('filter.category_id'));
$user = JFactory::getUser();
JToolBarHelper::title('Event Manager', 'generic.png');
JToolBarHelper::addNew('add');
if (count($user->getAuthorisedCategories('com_events', 'core.create')) > 0)
{
//JToolBarHelper::addNew('add');
}
if (($canDo->get('core.edit')))
{
JToolBarHelper::editList('edit');
}
if ($canDo->get('core.edit.state'))
{
if ($this->state->get('filter.state') != 2)
{
JToolBarHelper::divider();
JToolBarHelper::publish('publish', 'JTOOLBAR_PUBLISH', true);
JToolBarHelper::unpublish('unpublish', 'JTOOLBAR_UNPUBLISH', true);
}
}
if ($this->state->get('filter.state') == -2 && $canDo->get('core.delete'))
{
JToolBarHelper::deleteList('', 'remove', 'JTOOLBAR_EMPTY_TRASH');
JToolBarHelper::divider();
}
elseif ($canDo->get('core.edit.state'))
{
JToolBarHelper::trash('remove');
JToolBarHelper::divider();
}
}
function displayEdit($eventId,$tpl = NULL)
{
JToolBarHelper::title('Event'.': [<small>Edit</small>]');
JToolBarHelper::save();
JToolBarHelper::cancel();
$model = $this->getModel();
$event = $model->getEvent($eventId);
$this->event = $event;
parent::display($tpl);
}
function displayAdd($tpl = NULL){
JToolBarHelper::title('Event'.': [<small>Add</small>]');
JToolBarHelper::save();
JToolBarHelper::cancel();
parent::display($tpl);
}
}
default.php
<td colspan="9"><?php echo $this->pagination->getListFooter(); ?></td>
Can any help me what is wrong or what i am missing
This might be because the required Javascript frameworks aren't available. To ensure if this is the case, you can check your javascript console.
If that is the case, in your view extending JViewLegacy, before the line:
$this->pagination = $this->get('Pagination');
Insert below line:
JHtml::_('behavior.framework');
Also, make sure your template is not removing the required frameworks.
unset($doc->_scripts[JURI::root(true) . '/media/system/js/core.js']);
Comment out this line if you see it in your template index.php
Hope this helps :)
Extend class JModelList instead of JModelLegacy, that should sorry it out.
I am trying to do a simple pagination where it'll retrieve data from MySQL and show a previous and next button, no numbers for counting pages, although once the next button is pressed no information are updated, I am not sure if I should use a while or foreach loop.
query
pageClass.php
public function classname
{
$start_page = 0;
$per_page = 8;
if(!isset($_GET['page']))
{
$page = 1;
} else {
$page = $_GET['page'];
}
if($page<=1)
$start_page = 0;
else
$start_page = $page * $per_page - $per_page;
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sth = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$sth->execute(array($start_page, $per_page));
$row = $sth->fetchAll();
return $row;
}
then in a .php file I am displaying it this way, I get the titles but once the buttons are pressed, no other page is opened.
index.php
foreach($latestArticles as $article)
{
$title = $latest['title'];
echo '<div>'.$title.'</div>';
}
$prev = $page - 1;
$next = $page + 1;
echo "
<a href='?page=$prev'>prev</a>
<a href='?page=$next'>next</a>
";
I don't want to put div's in the php classes as it would be a pain to find each class in folders to edit. What am I doing wrong?
First i would recommend you to change your pageClass.php to something more abstract
<?PHP
class pageClass
{
private $db;
private $articlesPerPage = 8;
private $startPage = 0;
public function __construct($db)
{
#TODO check if $db is valid PDO
$this->db = $db;
}
public function setArticlesPerPage($articlesPerPage)
{
$this->articlesPerPage = $articlesPerPage;
}
public function setStartPage($startPage)
{
$this->startPage = $startPage;
}
public function getArticles()
{
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$query = $this->db->prepare("SELECT * FROM articles ORDER BY article_uid DESC LIMIT ?, ?");
$queryResult = $query->execute(array($this->startPage, $this->articlesPerPage));
return $queryResult;
}
}
Try to change your index.php to the following
<?PHP
$page = (int)$_GET['page'];
$pageClass = new pageClass($pdo);
if($page > 0)
{
$pageClass->setStartPage($page);
}
$lastestArticles = $pageClass->getArticles();
foreach($lastestArticles as $article)
{
echo '<div>'.$article['title'].'</div>';
}
echo 'prev';
echo 'next';
?>
NOTE: THIS IS EXAMPLE CODE. YOU SHOULD EDIT IT BEFORE COMMITING TO PRODUCTION
I downloaded a php view counter and I set it the database but when it comes to show the hits I am getting error. The documentation says
USAGE:
In your script, use reqire_once() to import this script, then call the
functions like PHPCount::AddHit(...); See each function for help.
*
Here is my demo.php where I want to show the view. But it is throwing
Notice: Undefined variable: pageID in C:\xampp\htdocs\test\demo.php on line 4
1
<?php
include_once("hit.php");
echo //this is what I added.
PHPCount::AddHit($pageID);
?>
The below is hit.php and what I wanna know is how can I show the views on the above demo.php?
<?php
/*
* USAGE:
* In your script, use reqire_once() to import this script, then call the
* functions like PHPCount::AddHit(...); See each function for help.
*
* NOTE: You must set the database credentials in the InitDB method.
*/
class PHPCount
{
/*
* Defines how many seconds a hit should be rememberd for. This prevents the
* database from perpetually increasing in size. Thirty days (the default)
* works well. If someone visits a page and comes back in a month, it will be
* counted as another unique hit.
*/
const HIT_OLD_AFTER_SECONDS = 2592000; // default: 30 days.
// Don't count hits from search robots and crawlers.
const IGNORE_SEARCH_BOTS = true;
// Don't count the hit if the browser sends the DNT: 1 header.
const HONOR_DO_NOT_TRACK = false;
private static $IP_IGNORE_LIST = array(
'127.0.0.1',
);
private static $DB = false;
private static function InitDB()
{
if(self::$DB)
return;
try
{
// TODO: Set the database login credentials.
self::$DB = new PDO(
'mysql:host=localhost;dbname=test',
'root', // Username
'', // Password
array(PDO::ATTR_PERSISTENT => true)
);
}
catch(Exception $e)
{
die('Failed to connect to phpcount database');
}
}
/*
* Adds a hit to a page specified by a unique $pageID string.
*/
public static function AddHit($pageID)
{
if(self::IGNORE_SEARCH_BOTS && self::IsSearchBot())
return false;
if(in_array($_SERVER['REMOTE_ADDR'], self::$IP_IGNORE_LIST))
return false;
if(
self::HONOR_DO_NOT_TRACK &&
isset($_SERVER['HTTP_DNT']) && $_SERVER['HTTP_DNT'] == "1"
) {
return false;
}
self::InitDB();
self::Cleanup();
self::CreateCountsIfNotPresent($pageID);
if(self::UniqueHit($pageID))
{
self::CountHit($pageID, true);
self::LogHit($pageID);
}
self::CountHit($pageID, false);
return true;
}
/*
* Returns (int) the amount of hits a page has
* $pageID - the page identifier
* $unique - true if you want unique hit count
*/
public static function GetHits($pageID, $unique = false)
{
self::InitDB();
self::CreateCountsIfNotPresent($pageID);
$q = self::$DB->prepare(
'SELECT hitcount FROM hits
WHERE pageid = :pageid AND isunique = :isunique'
);
$q->bindParam(':pageid', $pageID);
$q->bindParam(':isunique', $unique);
$q->execute();
if(($res = $q->fetch()) !== FALSE)
{
return (int)$res['hitcount'];
}
else
{
die("Missing hit count from database!");
return false;
}
}
/*
* Returns the total amount of hits to the entire website
* When $unique is FALSE, it returns the sum of all non-unique hit counts
* for every page. When $unique is TRUE, it returns the sum of all unique
* hit counts for every page, so the value that's returned IS NOT the
* amount of site-wide unique hits, it is the sum of each page's unique
* hit count.
*/
public static function GetTotalHits($unique = false)
{
self::InitDB();
$q = self::$DB->prepare(
'SELECT hitcount FROM hits WHERE isunique = :isunique'
);
$q->bindParam(':isunique', $unique);
$q->execute();
$rows = $q->fetchAll();
$total = 0;
foreach($rows as $row)
{
$total += (int)$row['hitcount'];
}
return $total;
}
/*====================== PRIVATE METHODS =============================*/
private static function IsSearchBot()
{
// Of course, this is not perfect, but it at least catches the major
// search engines that index most often.
$keywords = array(
'bot',
'spider',
'spyder',
'crawlwer',
'walker',
'search',
'yahoo',
'holmes',
'htdig',
'archive',
'tineye',
'yacy',
'yeti',
);
$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
foreach($keywords as $keyword)
{
if(strpos($agent, $keyword) !== false)
return true;
}
return false;
}
private static function UniqueHit($pageID)
{
$ids_hash = self::IDHash($pageID);
$q = self::$DB->prepare(
'SELECT time FROM nodupes WHERE ids_hash = :ids_hash'
);
$q->bindParam(':ids_hash', $ids_hash);
$q->execute();
if(($res = $q->fetch()) !== false)
{
if($res['time'] > time() - self::HIT_OLD_AFTER_SECONDS)
return false;
else
return true;
}
else
{
return true;
}
}
private static function LogHit($pageID)
{
$ids_hash = self::IDHash($pageID);
$q = self::$DB->prepare(
'SELECT time FROM nodupes WHERE ids_hash = :ids_hash'
);
$q->bindParam(':ids_hash', $ids_hash);
$q->execute();
$curTime = time();
if(($res = $q->fetch()) !== false)
{
$s = self::$DB->prepare(
'UPDATE nodupes SET time = :time WHERE ids_hash = :ids_hash'
);
$s->bindParam(':time', $curTime);
$s->bindParam(':ids_hash', $ids_hash);
$s->execute();
}
else
{
$s = self::$DB->prepare(
'INSERT INTO nodupes (ids_hash, time)
VALUES( :ids_hash, :time )'
);
$s->bindParam(':time', $curTime);
$s->bindParam(':ids_hash', $ids_hash);
$s->execute();
}
}
private static function CountHit($pageID, $unique)
{
$q = self::$DB->prepare(
'UPDATE hits SET hitcount = hitcount + 1 ' .
'WHERE pageid = :pageid AND isunique = :isunique'
);
$q->bindParam(':pageid', $pageID);
$unique = $unique ? '1' : '0';
$q->bindParam(':isunique', $unique);
$q->execute();
}
private static function IDHash($pageID)
{
$visitorID = $_SERVER['REMOTE_ADDR'];
return hash("SHA256", $pageID . $visitorID);
}
private static function CreateCountsIfNotPresent($pageID)
{
// Non-unique
$q = self::$DB->prepare(
'SELECT pageid FROM hits WHERE pageid = :pageid AND isunique = 0'
);
$q->bindParam(':pageid', $pageID);
$q->execute();
if($q->fetch() === false)
{
$s = self::$DB->prepare(
'INSERT INTO hits (pageid, isunique, hitcount)
VALUES (:pageid, 0, 0)'
);
$s->bindParam(':pageid', $pageID);
$s->execute();
}
// Unique
$q = self::$DB->prepare(
'SELECT pageid FROM hits WHERE pageid = :pageid AND isunique = 1'
);
$q->bindParam(':pageid', $pageID);
$q->execute();
if($q->fetch() === false)
{
$s = self::$DB->prepare(
'INSERT INTO hits (pageid, isunique, hitcount)
VALUES (:pageid, 1, 0)'
);
$s->bindParam(':pageid', $pageID);
$s->execute();
}
}
private static function Cleanup()
{
$last_interval = time() - self::HIT_OLD_AFTER_SECONDS;
$q = self::$DB->prepare(
'DELETE FROM nodupes WHERE time < :time'
);
$q->bindParam(':time', $last_interval);
$q->execute();
}
}
You may need to specify the PageID
PHPCount::AddHit("index");