Sending user data to database without Prepared statment - php

I am using the pagination class below with PDO OOP
<?php
class Paginator{
private $db;
public $page_no;//current page
public $limit;//record_per page
public $row_start;
public $total_rec;
public $query;
function __construct($con){
$this->db = $con;
}
//get total no of records
public function get_no_records($query){
$this->query = $query;
$stmt = $this->db->prepare($query);
$stmt->execute();
$row_num = $stmt->rowCount();
if($row_num > 0){
$this->total_rec = $row_num;
return $row_num;
}
}
public function get_data($limit,$page_no){
try {
$this->limit = $limit;
$this->page_no = $page_no;
if($this->limit == "all"){
$query = $this->query;
}
else{
$this->row_start = (($this->page_no-1) * $this->limit);
$query = $this->query . " LIMIT ". $this->row_start . "," . $this->limit;
}
$stmt = $this->db->prepare($query);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
//create an array to hold record
$results[] = $row;
}
$result = new stdClass();
$result->page_no = $this->page_no;
$result->limit = $this->limit;
$result->total_rec = $this->total_rec;
$result->data = $results;
return $result;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
public function create_links($links,$list_class){
if($this->limit == 'all'){
return '';
}
$last = ceil($this->total_rec/$this->limit);
$start = (($this->page_no - $links) > 0) ? $this->page_no - $links : 1;
$end = (($this->page_no + $links) < $last) ? $this->page_no + $links : $last;
$html = '<ul class="' . $list_class . '">';
$class = ($this->page_no == 1) ? "disabled" : "";
$previous_page = ($this->page_no == 1) ?
'<li class="' . $class . '">«</li>' :
'<li class="' . $class . '">«</li>';
$html .= $previous_page;
if($start > 1){
$html .= '<li>1</li>';
$html .= '<li class="disabled"><span>....</span></li>';
}
for($i = $start;$i<=$end;$i++){
$class = ($this->page_no == $i)? "active" : "";
$html .= '<li class="' . $class . '">' . $i . '</li>';
}
if( $end < $last){
$html .= '<li class="disabled"><span>....</span></li>';
$html .= '<li>' . $last . '</li>';
}
$class = ($this->page_no == $last)? "disabled" : "";
$next_page = ( $this->page_no == $last)?
'<li class="' . $class . '">»</li>':
'<li class="' . $class . '">»</li>';
$html .= $next_page;
$html .= '</ul>';
return $html;
}
}
?>
From the get_no_records($query) above any query passed is executed,I had a query like SELECT * FROM users and it worked fine. I have a function where the value of the column name is determined by the user input from a text field in a form
here is the function
public function search_user($value){
$query = "SELECT * FROM users WHERE username = " . "'" . $value . "'";
return $query;
}
Here is my search form
<form method="GET">
Username:<input type="text" name="uname"/>
<button type="submit" class="btn btn-primary" name="srch">Search</button>
</form>
The $query returned is passed to get_no_records($query) And it is working Fine.Here is My question. Is it right to send user input to the database that way? Is my code vulnerable to sql injection? How do i prevent this. Thanks.

You really need to use PDO prepared statements, as it is a reliable way to ensure that your website is safe from SQL Injection.
Reference: https://stackoverflow.com/a/3716402/5287820

Related

for loop not working correctly with json encode Php

I am trying to fetch members ratings from the database using ajax. I passed a function to the JSON, even though it returned a value in the function but it doesn't execute the for loop condition.
Here is my code, the loop failed to execute. What am I doing wrong?
function mrate($irate) {
$class = "fa-star star-filled";
for ($i = 0; $i < 5; $i++) {
if ($irate <= $i) {
$class = "fa-star-o empty";
}
return '<i class="fa ' . $class . '"></i>';
}
}
$perPage = 2;
if (isset($_GET["page"]) && isset($_GET["page"])) {
$page = $_GET["page"];
$pid = $mysqli->real_string_escape($_GET["pid"]);
} else {
$page = 1;
$pid = $mysqli->real_string_escape($_SESSION['pid']);
};
$startFrom = ($page - 1) * $perPage;
$sqlQuery = "SELECT id, name,
review, rating, added_date
FROM review_rating
where product_id = '$pid'
ORDER BY id ASC LIMIT $startFrom, $perPage";
$result = mysqli_query($mysqli, $sqlQuery);
$paginationHtml = '';
while ($row = mysqli_fetch_assoc($result)) {
$img = '<img class="rounded-circle" width="50" src="' . $set['installUrl'] . 'assets/img/login.png" alt="' . $row["name"] . '"/>';
$irate = $row['rating'];
$paginationHtml .= '<div class="product-review pb-4 mb-4 border-bottom">';
$paginationHtml .= '<div class="d-flex mb-3">';
$paginationHtml .= '<div class="media media-ie-fix align-items-center mr-4 pr-2">' . $img;
$paginationHtml .= '<div class="media-body pl-3"><h6 class="font-size-sm mb-0">' . $row["name"] . '</h6>';
$paginationHtml .= '<span class="font-size-ms text-muted">' . $row['added_date'] . '</span></div></div>';
$paginationHtml .= '<div><div class="star-rating">' . mrate($irate) . '</div></div>';
$paginationHtml .= '</div>';
$paginationHtml .= '<p class="font-size-md mb-2">' . $row['review'] . '</p>';
$paginationHtml .= '</div>';
}
$jsonData = array(
"html" => $paginationHtml,
);
echo json_encode($jsonData);
Replace your function mrate($irate) with this and try. You needed to concatenate the stars code to display it more than once.
function mrate($irate){
$stars = '';
for($i=0; $i<5; $i++){
if($irate <= $i){
$class = "fa-star-o empty";
}else{
$class = "fa-star star-filled";
}
$stars .= '<i class="fa '.$class.'"></i>';
}
return $stars;
}
Assuming there's no fractional rating, you can do the following - Display all 5 stars but solid ones will represent the rating.
function mrate($irate){
$class = '';
for($i = 0; $i < 5; $i++){
if ($irate <= $i) {
$class .= '<i class="fa fa-star"></i>';
} else {
$class .= '<i class="fa fa-star-o"></i>';
}
}
return $class;
}

PHP file breaks when using $_GET variable in URL

I am using a select dropdown menu to filter clinical trials from a database. Below the select is code that calls clinical_trial() class. Problem is that no results are being displayed when $_GET variable ?cid= is appended to the url.
clinical_trials.php
<?php if($_GET['cid']) $cid = $_GET['cid']; ?>
<?php
$query = "SELECT * FROM `category` ORDER BY category_name";
$categories = $_db->get_results($query, ARRAY_A); ?>
<select id="dynamic_select">
<option value="clinical_trials.php" selected>All Categories</option>
<?php
foreach($categories as $row):
extract($row);
echo '<option ' . ($cid == $category_id ? "selected" : "") . ' value="clinical_trials.php?cid='.$category_id.'">' . $category_name . '</option>';
endforeach; ?>
</select>
<script>
jQuery(document).ready(function($){
$('#dynamic_select').on('change', function () {
var url = $(this).val();
if (url) window.location = url; // redirect
return false;
});
});
</script>
<?php
$ct = new clinical_trial();
$params = array();
if($cid != '') $params['category_id'] = $cid;
$results = $ct->search($params);
$file_path = CLINICAL_TRIALS_REL_PATH;
$ts = strtotime($file_date);
if(count($results) > 0):
$html = '';
$html .= '<table id="current-clinicals">';
foreach($results as $row):
extract($row);
$html .= '<tr>';
$html .= '<td valign="top">'.$trial_name.'</td>';
$html .= '<td valign="top">'.$category_name.'</td>';
$html .= '<td valign="top">'.date("m/d/Y").'</td>';
$html .= '<td width="80" valign="top" align="center"><strong>View Here</strong></td>';
$html .= '</tr>';
endforeach;
else:
$html .= '<p>No clinical trials in this category.</p>';
endif;
$html .= '</table>';
echo $html; ?>
Below code is stored in clinical_trial.php
<?php
class clinical_trial{
public function validate($post, $file, &$errors, $action='create'){
global $_db;
cleanup_arr($post);
extract($post);
$errors = array();
$rules[] = array( 'rule'=>'', 'val'=>$lst_category_id, 'minlen'=>0, 'maxlen'=>0, 'required'=>true, 'friendly_name'=>'Category', 'var'=>'lst_category_id');
$rules[] = array( 'rule'=>'', 'val'=>$txt_trial_name, 'minlen'=>0, 'maxlen'=>0, 'required'=>true, 'friendly_name'=>'Trial name', 'var'=>'txt_trial_name');
$rules[] = array( 'rule'=>'', 'val'=>$txt_file_date, 'minlen'=>0, 'maxlen'=>0, 'required'=>true, 'friendly_name'=>'File date', 'var'=>'txt_file_date');
$flag_validated = true;
foreach($rules as $r){
$ret = validate($r);
$varname = $r['var'];
if($ret != VALIDATE_SUCCESS){
$flag_validated = false;
$errors[$varname] = $ret;
}
}
if ($action == 'create'){
if(!is_uploaded_file($file['file_filename']['tmp_name'])){
$flag_validated = false;
$errors['file_filename'] = 'Please upload a file.';
}
}
return $flag_validated;
}
function create($post, $file){
global $_db;
cleanup_arr($post);
extract($post);
$ts = strtotime($txt_file_date);
$file_date = date("Y-m-d", $ts);
$query = "INSERT INTO `clinical_trial` (trial_name, file_date, file_name, category_id) VALUES ('$txt_trial_name', '$file_date', '', $lst_category_id)";
$_db->query($query);
$clinical_trial_id = $_db->insert_id;
//$filename = md5(time());
$filename = $file_date . '-' . make_file_name($txt_trial_name);
$filename = handle_file_upload($file['file_filename'], $filename, CLINICAL_TRIALS_ABS_PATH);
$_db->query("UPDATE `clinical_trial` SET file_name='$filename' WHERE clinical_trial_id=$clinical_trial_id");
}
function update($post, $file){
global $_db;
cleanup_arr($post);
extract($post);
$ts = strtotime($txt_file_date);
$file_date = date("Y-m-d", $ts);
$query = "UPDATE `clinical_trial` SET trial_name='$txt_trial_name', category_id=$lst_category_id, file_date='$file_date' WHERE clinical_trial_id=$hdn_clinical_trial_id";
$_db->query($query);
if(is_uploaded_file($file['file_filename']['tmp_name'])){
#unlink(CLINICAL_TRIALS_ABS_PATH . $_db->get_var("SELECT file_name FROM clinical_trial WHERE clinical_trial_id=$hdn_clinical_trial_id"));
$filename = $file_date . '-' . make_file_name($txt_trial_name);
$filename = handle_file_upload($file['file_filename'], $filename, CLINICAL_TRIALS_ABS_PATH);
$_db->query("UPDATE `clinical_trial` SET file_name='$filename' WHERE clinical_trial_id=$hdn_clinical_trial_id");
}
}
function delete($clinical_trial_id){
global $_db;
cleanup_var($clinical_trial_id);
#unlink(CLINICAL_TRIALS_ABS_PATH . $_db->get_var("SELECT file_name FROM clinical_trial WHERE clinical_trial_id=$clinical_trial_id"));
$_db->query("DELETE FROM `clinical_trial` WHERE clinical_trial_id=$clinical_trial_id");
}
function search($params, $order_by=''){
global $_db;
if($params){
cleanup_arr($params);
extract($params);
}
if($category_id != '') $where = " AND ct.category_id=$category_id ";
$order_by = $order_by == "" ? "file_date DESC" : $order_by;
$query = "SELECT * FROM `clinical_trial` ct, `category` c
WHERE ct.category_id=c.category_id
$where
ORDER BY $order_by";
return $_db->get_results($query, ARRAY_A);
}
public function get($id)
{
global $_db;
cleanup_var($id);
$query = "SELECT * FROM `clinical_trial` ct WHERE ct.clinical_trial_id=$id";
$r = $_db->get_row($query, ARRAY_A);
if(count($r) == 0)
return false;
foreach ( $r as $key => $val ){
$this->$key = stripslashes($val);
}
return true;
}
} // class
You are not retrieving the $_GET variable?
Assuming this line is where you think you are retrieving it:
if($cid != '') $params['category_id'] = $cid;
From you code that condition will always be false.
Correct use would be:
if($_GET['cid'] != '') $params['category_id'] = $_GET['cid'];

Custom table sorting not working correct

I am creating a data table that has sortable links but when I click on the link say "username" if i click on that multiple times it makes the url have lots of asc example: http://localhost/riwakawebsitedesigns-website/admin/users/status/ascascascascascascasc it should just be
Sorting Asc http://localhost/riwakawebsitedesigns-website/admin/users/status/asc
And then if click again and so on.
Sorting Desc http://localhost/riwakawebsitedesigns-website/admin/users/status/desc
This here is how pagination looks in url http://localhost/riwakawebsitedesigns-website/admin/users/1
I cannot figure out why each time i click on table head link that it creates so many asc etc. How can I fix it.
What's wrong with sort code. The pagination works fine. Please note I have use codeigniter pagination but not to my liking.
<?php
class Users extends MX_Controller {
public function index() {
$this->getList();
}
public function getList() {
$this->load->library('paginations');
$sort_segment = $this->uri->segment(3);
if (isset($sort_segment)) {
$sort = $sort_segment;
} else {
$sort = 'username';
}
$order_segment = $this->uri->segment(3);
if (isset($order_segment)) {
$order = $order_segment;
} else {
$order = 'asc';
}
$page_segment = $this->uri->segment(4);
if (isset($page_segment)) {
$page = $page_segment;
} else {
$page = 1;
}
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['title'] = "Users";
$this->load->model('admin/user/model_user');
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'date_added' => $result['date_added'],
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'])
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
if (isset($page_segment)) {
$url .= $page_segment;
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
if (isset($sort_segment)) {
$url .= $sort_segment;
}
if (isset($order_segment)) {
$url .= $order_segment;
}
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = "1";
$paginations->url = site_url('admin/users' .'/'. $url .'/'. '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}
Thanks so much to #AdrienXL which gave me the idea what problem was.
I now have fixed it. I had doubled up on my page and sort and orders $_GET. So there for i have now just used uri segments and removed the doubled up code and change a couple of things in model
For people who do not want to use codeigniter pagination class.
You can use my example:
My Users:
<?php
class Users extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user');
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'username';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "1";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_total = $this->model_user->getTotalUsers();
$results = $this->model_user->getUsers($filter_data);
foreach ($results as $result) {
$data['users'][] = array(
'user_id' => $result['user_id'],
'username' => $result['username'],
'status' => ($result['status'] ? "Enabled" : "Disabled"),
'date_added' => date(strtotime($result['date_added'])),
'edit' => site_url('admin/users/edit' .'/'. $result['user_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_username'] = site_url('admin/users' .'/'. 'username' .'/'. $url);
$data['sort_status'] = site_url('admin/users' .'/'. 'status' .'/'. $url);
$data['sort_date_added'] = site_url('admin/users' .'/'. 'date_added' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_total - $admin_limit)) ? $user_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_total, ceil($user_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_list.tpl', $data);
}
}
My View
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<td class="text-left"><?php if ($sort == 'username') { ?>
Username
<?php } else { ?>
Username
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'status') { ?>
Status
<?php } else { ?>
Status
<?php } ?></td>
<td class="text-left"><?php if ($sort == 'date_added') { ?>
Date Added
<?php } else { ?>
Date Added
<?php } ?></td>
<td class="text-right">Action</td>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td><?php echo $user['username'];?></td>
<td><?php echo $user['status'];?></td>
<td><?php echo $user['date_added'];?></td>
<td><a href="<?php echo $user['edit'];?>">Edit</td>
</tr>
<?php } ?>
</tbody>
</table>
<div class="row">
<div class="col-sm-6 text-left"><?php echo $pagination; ?></div>
<div class="col-sm-6 text-right"><?php echo $results; ?></div>
</div>
</div>
Model Function
public function getUsers($data = array()) {
$sql = "SELECT * FROM `" . $this->db->dbprefix . "user`";
$sort_data = array(
'username',
'status',
'date_added'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY username";
}
if (isset($data['order']) && ($data['order'] == 'desc')) {
$sql .= " desc";
} else {
$sql .= " asc";
}
if (isset($data['start']) || isset($data['limit'])) {
if ($data['start'] < 0) {
$data['start'] = 0;
}
if ($data['limit'] < 1) {
$data['limit'] = 20;
}
$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
}
$query = $this->db->query($sql);
return $query->result_array();
}
Routes:
$route['admin/users'] = "admin/user/users/index";
$route['admin/users/edit/(:any)'] = "admin/user/users/edit/$1";
$route['admin/users/(:any)'] = "admin/user/users/index/$1";
$route['admin/users/(:any)/(:any)/(:any)'] = "admin/user/users/index/$1/$2/$3";
Custom Library
<?php
class Paginations {
public $total = 0;
public $page = 1;
public $limit = 20;
public $num_links = 8;
public $url = '';
public $text_first = '|<';
public $text_last = '>|';
public $text_next = '>';
public $text_prev = '<';
public function render() {
$total = $this->total;
if ($this->page < 1) {
$page = 1;
} else {
$page = $this->page;
}
if (!(int)$this->limit) {
$limit = 10;
} else {
$limit = $this->limit;
}
$num_links = $this->num_links;
$num_pages = ceil($total / $limit);
$this->url = str_replace('%7Bpage%7D', '{page}', $this->url);
$output = '<ul class="pagination">';
if ($page > 1) {
$output .= '<li>' . $this->text_first . '</li>';
$output .= '<li>' . $this->text_prev . '</li>';
}
if ($num_pages > 1) {
if ($num_pages <= $num_links) {
$start = 1;
$end = $num_pages;
} else {
$start = $page - floor($num_links / 2);
$end = $page + floor($num_links / 2);
if ($start < 1) {
$end += abs($start) + 1;
$start = 1;
}
if ($end > $num_pages) {
$start -= ($end - $num_pages);
$end = $num_pages;
}
}
for ($i = $start; $i <= $end; $i++) {
if ($page == $i) {
$output .= '<li class="active"><span>' . $i . '</span></li>';
} else {
$output .= '<li>' . $i . '</li>';
}
}
}
if ($page < $num_pages) {
$output .= '<li>' . $this->text_next . '</li>';
$output .= '<li>' . $this->text_last . '</li>';
}
$output .= '</ul>';
if ($num_pages > 1) {
return $output;
} else {
return '';
}
}
}

Php Pagination class and display issue

I have a php pagination class with code as follows:
<?php
class Pagination {
private $num_pages = 1;
private $start = 0;
private $display;
private $start_display;
function __construct ($query, $display=10) {
if (!empty($query)) {
$this->display = $display;
if (isset($_GET['display']) && is_numeric($_GET['display'])) $this->display = (int) $_GET['display'];
if (isset($_GET['np']) && is_numeric($_GET['np']) && $_GET['np'] > 0) {
$this->num_pages = (int) $_GET['np'];
} else {
if (is_numeric($query)) {
$num_records = $query;
} else {
$result = db_query ($query);
if ($result->num_rows > 1 || strstr($query, 'COUNT') === false) {
$num_records = $result->num_rows;
} else {
$row = $result->fetch_row();
$num_records = $row[0];
}
}
if ($num_records > $this->display) $this->num_pages = ceil ($num_records/$this->display);
}
if (isset($_GET['s']) && is_numeric($_GET['s']) && $_GET['s'] > 0) $this->start = (int) $_GET['s'];
$this->start_display = " LIMIT {$this->start}, {$this->display}";
}
}
public function display ($split=5) {
global $page;
$html = '';
if ($this->num_pages <= 1) return $html;
//$page->link('pagination.css');
$url = $page->url ('add', '', 'np', $this->num_pages);
$current_page = ($this->start/$this->display) + 1;
$begin = $current_page - $split;
$end = $current_page + $split;
if ($begin < 1) {
$begin = 1;
$end = $split * 2;
}
if ($end > $this->num_pages) {
$end = $this->num_pages;
$begin = $end - ($split * 2);
$begin++; // add one so that we get double the split at the end
if ($begin < 1) $begin = 1;
}
if ($current_page != 1) {
$html .= '<a class="first" title="First" href="' . $page->url('add', $url, 's', 0) . '">«</a>';
$html .= '<a class="prev" title="Previous" href="' . $page->url('add', $url, 's', $this->start - $this->display) . '">Previous</a>';
} else {
$html .= '<span class="disabled first" title="First">«</span>';
$html .= '<span class="disabled prev" title="Previous">Previous</span>';
}
for ($i=$begin; $i<=$end; $i++) {
if ($i != $current_page) {
$html .= '<a title="' . $i . '" href="' . $page->url('add', $url, 's', ($this->display * ($i - 1))) . '">' . $i . '</a>';
} else {
$html .= '<span class="current">' . $i . '</span>';
}
}
if ($current_page != $this->num_pages) {
$html .= '<a class="next" title="Next" href="' . $page->url('add', $url, 's', $this->start + $this->display) . '">Next</a>';
$last = ($this->num_pages * $this->display) - $this->display;
$html .= '<a class="last" title="Last" href="' . $page->url('add', $url, 's', $last) . '">»</a>';
} else {
$html .= '<span class="disabled next" title="Next">Next</span>';
$html .= '<span class="disabled last" title="Last">»</span>';
}
return '<div class="pagination">' . $html . '</div>';
}
public function limit () {
return $this->start_display;
}
}
?>
I am calling the class as follows:
$page->link('pagination.css');
$links = new Pagination ($numrows);
I have a mysql query with LIMIT as $links->limit() and it is displaying 10 records correctly.
I am calling pagination display as:
$html .= $links->display();
But no pagination is displayed and I am getting the following error:
PHP Notice: Undefined variable: page in ......
and
Call to a member function link() on a non-object on line
$page->link('pagination.css');
I have the pagination.css file uploaded in the same folder too....
What is wrong with my code ?? Why am i getting the Notice that php is undefined variable though having a global scope in the class method? And Call to a member function link() on a non-object ??
Thanks in advance.
Note: Got the pagination Class from the following link:
Pagination Class Source
You have created an Class Definition, but never created an Instance of this Class Definition.
you have to instantiate class ?$page? in PHP to get an Instance in form of an object of it. For your example code you have to hold (save) this object instance in an variable with name "page" which was previously defined with global keyword.
$html = "";
global $page;
$page->link('pagination.css');
$links = new Pagination ($numrows);
$html .= $page->display();
var_dump($html);
HTH
Tobias

How To Change Numbers Based On Results

I have a follow up question on something I got help with here the other day (No Table Three Column Category Layout).
The script is as follows:
$res = mysql_query($query);
$system->check_mysql($res, $query, __LINE__, __FILE__);
$parent_node = mysql_fetch_assoc($res);
$id = (isset($parent_node['cat_id'])) ? $parent_node['cat_id'] : $id;
$catalist = '';
if ($parent_node['left_id'] != 1)
{
$children = $catscontrol->get_children_list($parent_node['left_id'], $parent_node['right_id']);
$childarray = array($id);
foreach ($children as $k => $v)
{
$childarray[] = $v['cat_id'];
}
$catalist = '(';
$catalist .= implode(',', $childarray);
$catalist .= ')';
$all_items = false;
}
$NOW = time();
/*
specified category number
look into table - and if we don't have such category - redirect to full list
*/
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE cat_id = " . $id;
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$category = mysql_fetch_assoc($result);
if (mysql_num_rows($result) == 0)
{
// redirect to global categories list
header ('location: browse.php?id=0');
exit;
}
else
{
// Retrieve the translated category name
$par_id = $category['parent_id'];
$TPL_categories_string = '';
$crumbs = $catscontrol->get_bread_crumbs($category['left_id'], $category['right_id']);
for ($i = 0; $i < count($crumbs); $i++)
{
if ($crumbs[$i]['cat_id'] > 0)
{
if ($i > 0)
{
$TPL_categories_string .= ' > ';
}
$TPL_categories_string .= '' . $category_names[$crumbs[$i]['cat_id']] . '';
}
}
// get list of subcategories of this category
$subcat_count = 0;
$query = "SELECT * FROM " . $DBPrefix . "categories WHERE parent_id = " . $id . " ORDER BY cat_name";
$result = mysql_query($query);
$system->check_mysql($result, $query, __LINE__, __FILE__);
$need_to_continue = 1;
$cycle = 1;
$column = 1;
$TPL_main_value = '';
while ($row = mysql_fetch_array($result))
{
++$subcat_count;
if ($cycle == 1)
{
$TPL_main_value .= '<div class="col'.$column.'"><ul>' . "\n";
}
$sub_counter = $row['sub_counter'];
$cat_counter = $row['counter'];
if ($sub_counter != 0)
{
$count_string = ' (' . $sub_counter . ')';
}
else
{
if ($cat_counter != 0)
{
$count_string = ' (' . $cat_counter . ')';
}
else
{
$count_string = '';
}
}
if ($row['cat_colour'] != '')
{
$BG = 'bgcolor=' . $row['cat_colour'];
}
else
{
$BG = '';
}
// Retrieve the translated category name
$row['cat_name'] = $category_names[$row['cat_id']];
$catimage = (!empty($row['cat_image'])) ? '<img src="' . $row['cat_image'] . '" border=0>' : '';
$TPL_main_value .= "\t" . '<li>' . $catimage . '' . $row['cat_name'] . $count_string . '</li>' . "\n";
++$cycle;
if ($cycle == 7) // <---- here
{
$cycle = 1;
$TPL_main_value .= '</ul></div>' . "\n";
++$column;
}
}
if ($cycle >= 2 && $cycle <= 6) // <---- here minus 1
{
while ($cycle < 7) // <---- and here
{
$TPL_main_value .= ' <p> </p>' . "\n";
++$cycle;
}
$TPL_main_value .= '</ul></div>'.$number.'
' . "\n";
}
I was needing to divide the resulting links into three columns to fit my html layout.
We accomplished this by changing the numbers in the code marked with "// <---- here".
Because the amount of links returned could be different each time, I am trying to figure out how to change those numbers on the fly. I tried using
$number_a = mysql_num_rows($result);
$number_b = $number_a / 3;
$number_b = ceil($number_b);
$number_c = $number_b - 1;
and then replacing the numbers with $number_b or $number_c but that doesn't work. Any ideas?
As mentioned before, you can use the mod (%) function to do that.
Basically what it does is to get the remainder after division. So, if you say 11 % 3, you will get 2 since that is the remainder after division. You can then make use of this to check when a number is divisible by 3 (the remainder will be zero), and insert an end </div> in your code.
Here is a simplified example on how to use it to insert a newline after every 3 columns:
$cycle = 1;
$arr = range (1, 20);
$len = sizeof ($arr);
for ( ; $cycle <= $len; $cycle++)
{
echo "{$arr[$cycle - 1]} ";
if ($cycle % 3 == 0)
{
echo "\n";
}
}
echo "\n\n";

Categories