I am trying to add a new page in the admin section in opencart and have managed to create all the necessary files and permissions for it to show up, but it wont display any results. I am trying to make a page where I can add/edit/delete minecraft recipes. But instead of showing the results for each recipe in the database it just shows "No results!" Please help me i am stuck.
Database Table:
CREATE TABLE IF NOT EXISTS `oc_recipes` (
`recipe_id` int(255) NOT NULL AUTO_INCREMENT,
`item1` int(255) NOT NULL,
`item2` int(255) NOT NULL,
`item3` int(255) NOT NULL,
`item4` int(255) NOT NULL,
`item5` int(255) NOT NULL,
`item6` int(255) NOT NULL,
`item7` int(255) NOT NULL,
`item8` int(255) NOT NULL,
`item9` int(255) NOT NULL,
`product_id` int(11) NOT NULL,
`sort_order` int(255) NOT NULL,
PRIMARY KEY (`recipe_id`),
UNIQUE KEY `product_id` (`product_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `oc_recipes` (`recipe_id`, `item1`, `item2`, `item3`, `item4`, `item5`, `item6`, `item7`, `item8`, `item9`, `product_id`, `sort_order`) VALUES (1, 89, 0, 0, 0, 0, 0, 0, 0, 0, 90, 0);
admin/controller/catalog/recipe.php:
class ControllerCatalogRecipe extends Controller {
private $error = array();
public function index() {
$this->language->load('catalog/recipe');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('catalog/recipe');
$this->getList();
}
protected function getList() {
if (isset($this->request->get['sort'])) {
$sort = $this->request->get['sort'];
} else {
$sort = 'name';
}
if (isset($this->request->get['order'])) {
$order = $this->request->get['order'];
} else {
$order = 'ASC';
}
if (isset($this->request->get['page'])) {
$page = $this->request->get['page'];
} else {
$page = 1;
}
$url = '';
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('catalog/recipe', 'token=' . $this->session->data['token'] . $url, 'SSL')
);
$data['add'] = $this->url->link('catalog/recipe/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
$data['delete'] = $this->url->link('catalog/recipe/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');
$data['recipes'] = array();
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $this->config->get('config_limit_admin'),
'limit' => $this->config->get('config_limit_admin')
);
$recipe_total = $this->model_catalog_recipe->getTotalRecipes();
$results = $this->model_catalog_recipe->getRecipes($filter_data);
foreach ($results as $result) {
$data['recipes'][] = array(
'recipe_id' => $result['recipe_id'],
'name' => $this->model_catalog_recipe->getRecipeName($result['product_id']),
'sort_order' => $result['sort_order'],
'edit' => $this->url->link('catalog/recipe/edit', 'token=' . $this->session->data['token'] . '&recipe_id=' . $result['recipe_id'] . $url, 'SSL')
);
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_list'] = $this->language->get('text_list');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['text_confirm'] = $this->language->get('text_confirm');
$data['column_name'] = $this->language->get('column_name');
$data['column_sort_order'] = $this->language->get('column_sort_order');
$data['column_action'] = $this->language->get('column_action');
$data['button_add'] = $this->language->get('button_add');
$data['button_edit'] = $this->language->get('button_edit');
$data['button_delete'] = $this->language->get('button_delete');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
if (isset($this->request->post['selected'])) {
$data['selected'] = (array)$this->request->post['selected'];
} else {
$data['selected'] = array();
}
$url = '';
if ($order == 'ASC') {
$url .= '&order=DESC';
} else {
$url .= '&order=ASC';
}
if (isset($this->request->get['page'])) {
$url .= '&page=' . $this->request->get['page'];
}
$data['sort_name'] = $this->url->link('catalog/recipe', 'token=' . $this->session->data['token'] . '&sort=name' . $url, 'SSL');
$data['sort_sort_order'] = $this->url->link('catalog/recipe', 'token=' . $this->session->data['token'] . '&sort=sort_order' . $url, 'SSL');
$url = '';
if (isset($this->request->get['sort'])) {
$url .= '&sort=' . $this->request->get['sort'];
}
if (isset($this->request->get['order'])) {
$url .= '&order=' . $this->request->get['order'];
}
$pagination = new Pagination();
$pagination->total = $recipe_total;
$pagination->page = $page;
$pagination->limit = $this->config->get('config_limit_admin');
$pagination->url = $this->url->link('catalog/recipe', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
$data['pagination'] = $pagination->render();
$data['results'] = sprintf($this->language->get('text_pagination'), ($recipe_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($recipe_total - $this->config->get('config_limit_admin'))) ? $recipe_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $recipe_total, ceil($recipe_total / $this->config->get('config_limit_admin')));
$data['sort'] = $sort;
$data['order'] = $order;
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('catalog/recipe_list.tpl', $data));
}
}
admin/language/english/catalog/recipe.php:
// Heading
$_['heading_title'] = 'Recipes';
// Text
$_['text_success'] = 'Success: You have modified a recipe!';
$_['text_list'] = 'Recipe List';
$_['text_add'] = 'Add Recipe';
$_['text_edit'] = 'Edit Recipe';
$_['text_default'] = 'Default';
$_['text_percent'] = 'Percentage';
$_['text_amount'] = 'Fixed Amount';
// Column
$_['column_name'] = 'Recipe Name';
$_['column_sort_order'] = 'Sort Order';
$_['column_action'] = 'Action';
// Entry
$_['entry_name'] = 'Recipe Name';
$_['entry_store'] = 'Stores';
$_['entry_keyword'] = 'SEO Keyword';
$_['entry_image'] = 'Image';
$_['entry_sort_order'] = 'Sort Order';
$_['entry_type'] = 'Type';
// Help
$_['help_keyword'] = 'Do not use spaces, instead replace spaces with - and make sure the keyword is globally unique.';
// Error
$_['error_permission'] = 'Warning: You do not have permission to modify recipes!';
$_['error_name'] = 'Recipe Name must be between 2 and 64 characters!';
$_['error_keyword'] = 'SEO keyword already in use!';
$_['error_product'] = 'Warning: This recipe cannot be deleted as it is currently assigned to %s products!';
admin/model/catalog/recipe.php:
class ModelCatalogRecipe extends Model {
public function getRecipe($recipe_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "recipes");
return $query->row;
}
public function getRecipes($data = array()) {
$sql = "SELECT * FROM " . DB_PREFIX . "recipes";
if (!empty($data['filter_name'])) {
$sql .= " WHERE name LIKE '" . $this->db->escape($data['filter_name']) . "%'";
}
$sort_data = array(
'name',
'sort_order'
);
if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
$sql .= " ORDER BY " . $data['sort'];
} else {
$sql .= " ORDER BY name";
}
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->rows;
}
public function getRecipeName($product_id) {
$sql = "SELECT name FROM " . DB_PREFIX . "product_description WHERE product_id = ".$product_id;
$query = $this->db->query($sql);
return $query->row['name'];
}
public function getTotalRecipes() {
$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "recipes");
return $query->row['total'];
}
}
admin/view/template/catalog/recipe_list.tpl:
<?php echo $header; ?><?php echo $column_left; ?>
<div id="content">
<div class="page-header">
<div class="container-fluid">
<div class="pull-right"><i class="fa fa-plus"></i>
<button type="button" data-toggle="tooltip" title="<?php echo $button_delete; ?>" class="btn btn-danger" onclick="confirm('<?php echo $text_confirm; ?>') ? $('#form-recipe').submit() : false;"><i class="fa fa-trash-o"></i></button>
</div>
<h1><?php echo $heading_title; ?></h1>
<ul class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ul>
</div>
</div>
<div class="container-fluid">
<?php if ($error_warning) { ?>
<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <?php echo $error_warning; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<?php if ($success) { ?>
<div class="alert alert-success"><i class="fa fa-check-circle"></i> <?php echo $success; ?>
<button type="button" class="close" data-dismiss="alert">×</button>
</div>
<?php } ?>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-list"></i> <?php echo $text_list; ?></h3>
</div>
<div class="panel-body">
<form action="<?php echo $delete; ?>" method="post" enctype="multipart/form-data" id="form-manufacturer">
<div class="table-responsive">
<table class="table table-bordered table-hover">
<thead>
<tr>
<td style="width: 1px;" class="text-center"><input type="checkbox" onclick="$('input[name*=\'selected\']').prop('checked', this.checked);" /></td>
<td class="text-left"><?php if ($sort == 'name') { ?>
<?php echo $column_name; ?>
<?php } else { ?>
<?php echo $column_name; ?>
<?php } ?></td>
<td class="text-right"><?php if ($sort == 'sort_order') { ?>
<?php echo $column_sort_order; ?>
<?php } else { ?>
<?php echo $column_sort_order; ?>
<?php } ?></td>
<td class="text-right"><?php echo $column_action; ?></td>
</tr>
</thead>
<tbody>
<?php if ($recipes) { ?>
<?php foreach ($recipes as $recipe) { ?>
<tr>
<td class="text-center"><?php if (in_array($recipe['recipe_id'], $selected)) { ?>
<input type="checkbox" name="selected[]" value="<?php echo $recipe['recipe_id']; ?>" checked="checked" />
<?php } else { ?>
<input type="checkbox" name="selected[]" value="<?php echo $recipe['recipe_id']; ?>" />
<?php } ?></td>
<td class="text-left"><?php echo $recipe['name']; ?></td>
<td class="text-right"><?php echo $recipe['sort_order']; ?></td>
<td class="text-right"><i class="fa fa-pencil"></i></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td class="text-center" colspan="4"><?php echo $text_no_results; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</form>
<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>
</div>
-EDIT-
On the View page I printed out $recipes and it just displays array(), so I am guessing the problem is somewhere inside the Controller where $recipes gets its data inserted into it. But as far as I can tell it looks like its all set up correctly! I am confused lol.
you need enable controller in admin panel to display your controller
admin menu > Setting> user group> enable your controller
after that you can open your new page by this pattern
[admin url]/index.php?route=catalog/recipe
Related
I've added clients in clients.php sown on the following screenshot:
UPDATE: If I add new client from manange_sale page, The List Shows up soon after!
When I try to access them in another page through this function:
function get_client_info($client_id, $term) {
global $db;
$query = "SELECT * from clients WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
$row = $result->fetch_array();
return $row[$term];
}
It just does not show any clients list on that page:
Please help me resolve this issue.
Note: Same script is working perfectly on Online host but causing issues in localhost.
Rest of the client class:
<?php
//Notes Class
class Client {
public $full_name;
public $business_title;
public $mobile;
public $phone;
public $address;
public $city;
public $state;
public $zipcode;
public $country;
public $email;
public $price_level;
public $notes;
function get_client_info($client_id, $term) {
global $db;
$query = "SELECT * from clients WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
$row = $result->fetch_array();
return $row[$term];
}//get user email ends here.
function add_client($full_name, $business_title, $mobile, $phone, $address, $city, $state, $zipcode, $country, $email, $price_level, $notes) {
global $db;
$query = "SELECT * from clients WHERE full_name='".$full_name."' AND store_id='".$_SESSION['store_id']."'";
$result = $db->query($query) or die($db->error);
$num_rows = $result->num_rows;
if($num_rows > 0) {
return 'A client with same name already exists.';
} else {
$query = "INSERT into clients(client_id, full_name, business_title, mobile, phone, address, city, state, zipcode, country, email, price_level, notes, store_id)
VALUES(NULL, '".$full_name."', '".$business_title."', '".$mobile."', '".$phone."', '".$address."', '".$city."', '".$state."', '".$zipcode."', '".$country."', '".$email."', '".$price_level."', '".$notes."', '".$_SESSION['store_id']."')
";
$result = $db->query($query) or die($db->error);
$_SESSION['cn_id'] = $db->insert_id;
return 'Client added successfuly.';
}
}//add warehouse ends here.
function set_client($client_id) {
global $db;
$query = 'SELECT * from clients WHERE client_id="'.$client_id.'" AND store_id="'.$_SESSION['store_id'].'"';
$result = $db->query($query) or die($db->error);
$row = $result->fetch_array();
extract($row);
$this->full_name = $full_name;
$this->business_title = $business_title;
$this->mobile = $mobile;
$this->phone = $phone;
$this->address = $address;
$this->city = $city;
$this->state = $state;
$this->zipcode = $zipcode;
$this->country = $country;
$this->email = $email;
$this->price_level = $price_level;
$this->notes = $notes;
}//Set Warehouse ends here..
function update_client($client_id, $full_name, $business_title, $mobile, $phone, $address, $city, $state, $zipcode, $country, $email, $price_level, $notes) {
global $db;
$query = 'UPDATE clients SET
full_name = "'.$full_name.'",
business_title = "'.$business_title.'",
mobile = "'.$mobile.'",
phone = "'.$phone.'",
address = "'.$address.'",
city = "'.$city.'",
state = "'.$state.'",
zipcode = "'.$zipcode.'",
country = "'.$country.'",
email = "'.$email.'",
price_level = "'.$price_level.'",
notes = "'.$notes.'"
WHERE client_id="'.$client_id.'" AND store_id="'.$_SESSION['store_id'].'"';
$result = $db->query($query) or die($db->error);
return 'Client updated Successfuly!';
}//update user level ends here.
function list_clients() {
global $db;
$query = 'SELECT * from clients WHERE store_id="'.$_SESSION['store_id'].'" ORDER by full_name ASC';
$result = $db->query($query) or die($db->error);
$content = '';
$count = 0;
while($row = $result->fetch_array()) {
extract($row);
$count++;
if($count%2 == 0) {
$class = 'even';
} else {
$class = 'odd';
}
$content .= '<tr class="'.$class.'">';
$content .= '<td>';
$content .= $client_id;
$content .= '</td><td>';
$content .= $full_name;
$content .= '</td><td>';
$content .= $business_title;
$content .= '</td><td>';
$content .= $mobile;
$content .= '</td><td>';
$content .= $phone;
$content .= '</td><td>';
$content .= $address.' '.$city.' '.$state.' '.$zipcode.' '.$country;
$content .= '</td><td>';
$content .= $email;
$content .= '</td><td>';
$content .= $price_level;
$content .= '</td><td>';
$content .= currency_format($this->get_client_balance($client_id));
$content .= '</td>';
if(partial_access('admin')) {
$content .= '<td><form method="post" name="edit" action="manage_client.php">';
$content .= '<input type="hidden" name="edit_client" value="'.$client_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Edit">';
$content .= '</form>';
$content .= '</td><td>';
$content .= '<form method="post" name="delete" onsubmit="return confirm_delete();" action="">';
$content .= '<input type="hidden" name="delete_client" value="'.$client_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Delete">';
$content .= '</form>';
$content .= '</td>';
}
$content .= '</tr>';
unset($class);
}//loop ends here.
echo $content;
}//list_notes ends here.
function delete_client($client_id) {
global $db;
$query = "SELECT * FROM customer_log WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
$num_rows = $result->num_rows;
if($num_rows > 0) {
return 'Please delete sale invoices, receivings, return invoices, return payments for related client first.';
} else {
$query = "DELETE FROM clients WHERE client_id='".$client_id."'";
$result = $db->query($query) or die($db->error);
return 'Client deleted successfuly!';
}
}//delete client ends here.
function client_options($client_id) {
global $db;
$query = 'SELECT * from clients WHERE store_id="'.$_SESSION['store_id'].'" ORDER by full_name ASC';
$result = $db->query($query) or die($db->error);
$options = '';
if($client_id != '') {
while($row = $result->fetch_array()) {
if($client_id == $row['client_id']) {
$options .= '<option selected="selected" value="'.$row['client_id'].'">'.$row['full_name'].' ('.$row['mobile'].')</option>';
} else {
$options .= '<option value="'.$row['client_id'].'">'.$row['full_name'].' ('.$row['mobile'].')</option>';
}
}
} else {
while($row = $result->fetch_array()) {
$options .= '<option value="'.$row['client_id'].'">'.$row['full_name'].' ('.$row['mobile'].')</option>';
}
}
return $options;
}//vendor options ends here.
function add_log($datetime, $client_id, $transaction_type, $type_table_id) {
global $db;
$query = "INSERT into customer_log(customer_log_id, datetime, client_id, transaction_type, type_table_id, store_id) VALUES(NULL, '".$datetime."', '".$client_id."', '".$transaction_type."', '".$type_table_id."', '".$_SESSION['store_id']."')";
$result = $db->query($query) or die($db->error);
return $db->insert_id;
}//add log ends here.
function add_receiving($date, $method, $ref_no, $memo, $amount, $client_id) {
global $db;
$query = "INSERT into receivings(receiving_id, datetime, method, ref_no, memo, amount, client_id, agent_id, store_id) VALUES(NULL, '".$date."', '".$method."', '".$ref_no."', '".$memo."', '".$amount."', '".$client_id."', '".$_SESSION['user_id']."', '".$_SESSION['store_id']."')";
$result = $db->query($query) or die($db->error);
return $db->insert_id;
}//add_payment ends here.
function add_return_payment($date, $method, $ref_no, $memo, $amount, $client_id) {
global $db;
$query = "INSERT into sale_return_payment(return_payment_id, datetime, method, ref_no, memo, amount, client_id, agent_id, store_id) VALUES(NULL, '".$date."', '".$method."', '".$ref_no."', '".$memo."', '".$amount."', '".$client_id."', '".$_SESSION['user_id']."', '".$_SESSION['store_id']."')";
$result = $db->query($query) or die($db->error);
return $db->insert_id;
}//add_payment ends here.
function get_client_balance($client_id) {
global $db;
$creditQuery = "SELECt * from creditors WHERE client_id='".$client_id."' AND store_id='".$_SESSION['store_id']."'";
$creditResult = $db->query($creditQuery) or die($db->error);
$receiveable = 0;
while($creditRow = $creditResult->fetch_array()) {
$receiveable += $creditRow['receiveable'];
if($creditRow['receiveable'] == 0) {
$receiveable -= $creditRow['received'];
}
}
$receivingQuery = "SELECt * from receivings WHERE client_id='".$client_id."' AND store_id='".$_SESSION['store_id']."'";
$receivingResult = $db->query($receivingQuery) or die($db->error);
while($recevingRow = $receivingResult->fetch_array()) {
$receiveable -= $recevingRow['amount'];
}
$sale_return_payment = "SELECt * from sale_return_payment WHERE client_id='".$client_id."' AND store_id='".$_SESSION['store_id']."'";
$sale_payment_result = $db->query($sale_return_payment) or die($db->error);
while($sale_return_row = $sale_payment_result->fetch_array()) {
$receiveable -= $sale_return_row['amount'];
}
return $receiveable;
}//get vendor balance ends here.
function list_receivings() {
global $db;
$query = 'SELECT * from receivings WHERE store_id="'.$_SESSION['store_id'].'" ORDER by receiving_id DESC';
$result = $db->query($query) or die($db->error);
$content = '';
while($row = $result->fetch_array()) {
extract($row);
$datetime = strtotime($datetime);
$date = date('d-M-Y', $datetime);
$client = $this->get_client_info($client_id, 'full_name');
$user = new Users;
$agent = $user->get_user_info($agent_id, 'first_name').' '.$user->get_user_info($agent_id, 'last_name');
$content .= '<tr><td>';
$content .= $receiving_id;
$content .= '</td><td>';
$content .= $date;
$content .= '</td><td>';
$content .= $method;
$content .= '</td><td>';
$content .= $ref_no;
$content .= '</td><td>';
$content .= $agent;
$content .= '</td><td>';
$content .= $client;
$content .= '</td><td>';
$content .= $memo;
$content .= '</td><td>';
$content .= $amount;
$content .= '</td>';
if(partial_access('admin')) {
$content .= '<td><form method="post" name="delete" onsubmit="return confirm_delete();" action="">';
$content .= '<input type="hidden" name="delete_receiving" value="'.$receiving_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Delete">';
$content .= '</form>';
$content .= '</td>'; }
$content .= '</tr>';
unset($class);
}//loop ends here.
echo $content;
}//list_notes ends here.
function delete_receiving($receiving_id) {
global $db;
$query = "DELETE from receivings WHERE receiving_id='".$receiving_id."'";
$result = $db->query($query) or die($db->error);
$query = "DELETE from customer_log WHERE transaction_type='Sale Receiving' AND type_table_id='".$receiving_id."'";
$result = $db->query($query) or die($db->error);
$query = "DELETE from customer_log WHERE transaction_type='Receiving' AND type_table_id='".$receiving_id."'";
$result = $db->query($query) or die($db->error);
return 'Receiving deleted Successfuly.';
}//delete_purchase return receiving.
function list_return_payments() {
global $db;
$query = 'SELECT * from sale_return_payment WHERE store_id="'.$_SESSION['store_id'].'" ORDER by return_payment_id DESC';
$result = $db->query($query) or die($db->error);
$content = '';
while($row = $result->fetch_array()) {
extract($row);
$datetime = strtotime($datetime);
$date = date('d-M-Y', $datetime);
$client = $this->get_client_info($client_id, 'full_name');
$user = new Users;
$agent = $user->get_user_info($agent_id, 'first_name').' '.$user->get_user_info($agent_id, 'last_name');
$content .= '<tr><td>';
$content .= $return_payment_id;
$content .= '</td><td>';
$content .= $date;
$content .= '</td><td>';
$content .= $method;
$content .= '</td><td>';
$content .= $ref_no;
$content .= '</td><td>';
$content .= $agent;
$content .= '</td><td>';
$content .= $client;
$content .= '</td><td>';
$content .= $memo;
$content .= '</td><td>';
$content .= $amount;
$content .= '</td>';
if(partial_access('admin')) {
$content .= '<td><form method="post" name="delete" onsubmit="return confirm_delete();" action="">';
$content .= '<input type="hidden" name="delete_sale_return_payment" value="'.$return_payment_id.'">';
$content .= '<input type="submit" class="btn btn-default btn-sm" value="Delete">';
$content .= '</form>';
$content .= '</td>'; }
$content .= '</tr>';
}//loop ends here.
echo $content;
}//list_notes ends here.
function delete_sale_return_payment($return_payment_id) {
global $db;
$query = "DELETE from sale_return_payment WHERE return_payment_id='".$return_payment_id."'";
$result = $db->query($query) or die($db->error);
$query = "DELETE from customer_log WHERE transaction_type='Sale Return Refund' AND type_table_id='".$return_payment_id."'";
$result = $db->query($query) or die($db->error);
return 'Return Payment deleted Successfuly.';
}//delete_purchase return receiving.
function clear_creditors($amount, $client_id){
global $db;
$query = "SELECT * FROM creditors WHERE client_id='".$client_id."' ORDER by credit_id ASC";
$result = $db->query($query) or die($db->error);
while($row = $result->fetch_array()) {
extract($row);
if($receiveable == 0 || $receiveable == $received || $amount == 0) {
//do nothing.
} else {
if($received == 0) {
if($amount < $receiveable) {
$receive = $amount;
} else {
$receive = $receiveable;
}
$query_up = "UPDATE creditors SET
received = '".$receive."'
WHERE credit_id='".$credit_id."'
";
$amount -= $receive;
} else if($received != 0) {
$difference = $receiveable-$received;
if($amount < $difference) {
$receive = $amount+$received;
} else {
$receive = $difference+$received;
}
$query_up = "UPDATE creditors SET
received = '".$receive."'
WHERE credit_id='".$credit_id."'
";
$amount -= $difference;
}
$result_up = $db->query($query_up) or die($db->error);
}//main if ends here.
}//main loop ends.
}//debts clear ends here.--
function customers_balance_summary() {
global $db;
$query = "SELECT * FROM clients WHERE store_id='".$_SESSION['store_id']."' ORDER by full_name ASC";
$result = $db->query($query) or die($db->error);
$content = '';
$grand_total = 0;
while($row = $result->fetch_array()) {
extract($row);
//getting balance.
$balance = $this->get_client_balance($client_id);
$grand_total += $balance;
$content .= '<tr><td>';
$content .= $full_name;
$content .= '</td><td>';
$content .= $business_title;
$content .= '</td><td align="right">';
$content .= currency_format($grand_total);
$content .= '</td></tr>';
}
$new_store = new Store;
$currency = $new_store->get_store_info($_SESSION['store_id'], 'currency');
$content .= '<tr><th colspan="2" align="right">Grand Total</th><th align="right">'.$currency.' '.currency_format($grand_total).'</tH></tr>';
echo $content;
}//customers balance summary ends here.
function customer_ledger_summary($client) {
global $db;
$query = "SELECT * from customer_log WHERE client_id='".$client."' ORDER by customer_log_id ASC";
$result = $db->query($query) or die($db->error);
$balance = 0;
$content = '';
$balance = 0;
while($row = $result->fetch_array()) {
extract($row);
$datetime = strtotime($datetime);
$date = date('d-M-Y', $datetime);
$content .= '<tr><td>';
$content .= $transaction_type;
$content .= '</td><td>';
$content .= $date;
$content .= '</td><td>';
$content .= $type_table_id;
$content .= '</td><td>';
if($transaction_type == 'Sale Invoice' || $transaction_type == 'Cash Sale') {
//Invoice Details.
$sale_query = "SELECT * from sales WHERE sale_id='".$type_table_id."'";
$sale_result = $db->query($sale_query) or die($db->error);
while($sale_row = $sale_result->fetch_array()) {
$content .= $sale_row['memo'];
$content .= '</td><td>';
}
$sale_detail_query = "SELECT * from sale_detail WHERE sale_id='".$type_table_id."'";
$sale_detail_result = $db->query($sale_detail_query) or die($db->error);
$invoice_total = 0;
while($sale_detail_row = $sale_detail_result->fetch_array()) {
$credit_query = "SELECT * from creditors WHERE credit_id='".$sale_detail_row['credit_id']."'";
$credit_result = $db->query($credit_query) or die($db->error);
while($credit_row = $credit_result->fetch_array()) {
$invoice_total += $credit_row['receiveable'];
}
}
$balance = $invoice_total+$balance;
$content .= currency_format($invoice_total);
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
} else if($transaction_type == 'Sale Receiving' || $transaction_type == 'Receiving') {
//Cash receivign.
$receiving_query = "SELECT * from receivings WHERE receiving_id='".$type_table_id."'";
$receiving_result = $db->query($receiving_query) or die($db->error);
while($receiving_row = $receiving_result->fetch_array()) {
$content .= $receiving_row['memo'];
$content .= '</td><td>';
$balance = $balance-$receiving_row['amount'];
$content .= '('.currency_format($receiving_row['amount']).')';
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
}
} else if($transaction_type == 'Invoice Return' || $transaction_type == 'Sale Return') {
//sale return invoice.
$sale_query = "SELECT * from sale_returns WHERE sale_rt_id='".$type_table_id."'";
$sale_result = $db->query($sale_query) or die($db->error);
while($sale_row = $sale_result->fetch_array()) {
$content .= $sale_row['memo'];
$content .= '</td><td>';
}
$sale_detail_query = "SELECT * from sale_return_detail WHERE sale_rt_id='".$type_table_id."'";
$sale_detail_result = $db->query($sale_detail_query) or die($db->error);
$invoice_total = 0;
while($sale_detail_row = $sale_detail_result->fetch_array()) {
$credit_query = "SELECT * from creditors WHERE credit_id='".$sale_detail_row['credit_id']."'";
$credit_result = $db->query($credit_query) or die($db->error);
while($credit_row = $credit_result->fetch_array()) {
$invoice_total += $credit_row['received'];
}
}
$balance = $balance-$invoice_total;
$content .= '('.currency_format($invoice_total).')';
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
} else if($transaction_type == 'Sale Return Refund') {
//sale Return Payment.
$receiving_query = "SELECT * from sale_return_payment WHERE return_payment_id='".$type_table_id."'";
$receiving_result = $db->query($receiving_query) or die($db->error);
while($receiving_row = $receiving_result->fetch_array()) {
$content .= $receiving_row['memo'];
$content .= '</td><td>';
$balance = $balance+$receiving_row['amount'];
$content .= currency_format($receiving_row['amount']);
$content .= '</td><td>';
$content .= currency_format($balance);
$content .= '</td></tr>';
}
}
}//main loop ends here.
echo $content;
}//customer ledger summary ends here.
}//class ends here.
The shown screen code where this class functions are being used:
`
<?php
include('system_load.php');
//This loads system.
//user Authentication.
authenticate_user('subscriber');
//creating company object.
if(partial_access('admin') || $store_access->have_module_access('sales')) {} else {
HEADER('LOCATION: store.php?message=products');
}
if(!isset($_SESSION['store_id']) || $_SESSION['store_id'] == '') {
HEADER('LOCATION: stores.php?message=1');
} //select company redirect ends here.
if(isset($_POST['edit_purchase'])){ $page_title = 'Edit Sale'; } else { $page_title = 'Add Sale';}; //You can edit this to change your page title.
require_once("includes/header.php"); //including header file.
?>
<?php if(isset($_GET['sale_id'])) { ?>
<script type="text/javascript">
window.open('reports/view_sale_invoice.php?sale_id=<?php echo $_GET['sale_id']; ?>', '_blank');
</script>
<?php } ?>
<?php
//display message if exist.
if(isset($_GET['message']) && $_GET['message'] != '') {
echo '<div class="alert alert-success">';
echo $_GET['message'];
echo '</div>';
}
if(isset($message) && $message != '') {
echo '<div class="alert alert-success">';
echo $message;
echo '</div>';
}
?>
<style type="text/css">
textarea:hover, textarea:focus, #items td.total-value textarea:hover, #items td.total-value textarea:focus, .delme:hover { background-color:#EEFF88; }
#items input[type=text] {width:60px;border:0px;}
.delete-wpr { position: relative; }
.delme { display: block; color: #000; text-decoration: none; position: absolute; background: #EEEEEE; font-weight: bold; padding: 0px 3px; border: 1px solid; top: -6px; left: -22px; font-family: Verdana; font-size: 12px; }
</style>
<script type="text/javascript">
jQuery(function($) {
$('form[data-async]').on('submit', function(event) {
var $form = $(this);
var $target = $($form.attr('data-target'));
$.ajax({
type: $form.attr('method'),
url: 'includes/otherprocesses.php',
data: $form.serialize(),
dataType: 'json',
success: function(response) {
var message = response.message;
var client_options = response.client_options;
var client_id = response.client_id;
$('#client_id').html(client_options);
$("#client_id").select2().select2('val', client_id);
$('#success_message').html('<div class="alert alert-success">'+message+'</div>');
}
});
event.preventDefault();
});
});
</script>
<!-- Add new vendor modal starts here. -->
<div class="modal fade" id="addnewclient" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Add new client</h4>
</div>
<div class="modal-body">
<form data-async data-target="#addnewclient" method="POST" enctype="multipart/form-data" role="form">
<div id="success_message"></div>
<table style="width:100%;">
<tr>
<td>
<div class="form-group">
<label class="control-label">Full Name*</label>
<input type="text" class="form-control" name="full_name" placeholder="Client full name" value="" required="required" />
</div>
</td>
<td>
<div class="form-group">
<label class="control-label">Business Title</label>
<input type="hidden" name="add_client" value="1" />
<input type="submit" id="submit" class="btn btn-primary" value="Add client">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--add new vendor modal ends here.-->
<form action="includes/process_sale.php" method="post">
<div class="row">
<div class="col-sm-5">
<table border="0" cellpadding="5">
<tr>
<td width="110">Date</td>
<td width="300"><input type="text" name="date" class="form-control datepick" readonly="readonly" value="<?php echo date('Y-m-d'); ?>" /></td>
</tr>
<tr>
<td>Custom Inv#</td>
<td><input type="text" placeholder="Custom Invoice number" name="custom_inv_no" class="form-control" /></td>
</tr>
<tr>
<td>Memo</td>
<td><textarea placeholder="Memo" name="memo" class="form-control"></textarea></td>
</tr>
<tr>
<th>Select Client</th>
<td>
<select name="client_id" id="client_id" class="autofill" style="width:100%">
<option value="">Select Client by full name or mobile</option>
<?
=$client->client_options($client->client_id);
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><a class="btn btn-default btn-xs" data-toggle="modal" href="#addnewclient">Add new Client</a></td>
</tr>
</table>
</div><!--left-side-form ends here.-->
<script type="text/javascript">
function update_total() {
var grand_total = 0;
i = 1;
$('.total').each(function(i) {
var total = $(this).html();
total = parseFloat(total);
grand_total = total+grand_total;
});
$('#grand_total').html(grand_total.toFixed(2));
}//Update total function ends here.
<?php
require_once("includes/footer.php");
?>
What plattform do you use for the localhost? Online linux server and local a Windows machine? As it is run on the localhost, do you get warnings, notices or the sort? Or even a fatal?
<?
=$client->client_options($client->client_id);
?>
That looks odd. Why the '='?
Okay I finally figured how to make it work by the hint provided above. Actually this Syntax doesn't work in this case:
<?=$client->client_options($client->client_id);?>
The Solution is:
<?php echo $client->client_options($client->client_id); ?>
Thanks all anyway for brainstorming.
I've got a website with a database over different phones. I would like to make a dropdown that will let the consumer sort and show/hide the phones after brand. I've created the dropdown as i want it, but my website isn't programmed by me, and i have very little experience with programming, so I really hope one of you guys or girls will help me out with how to code the PHP part.
I have a table that gets filled by a function in my home.php document, the whole function looks like this:
public function filter()
{
$price = $this->input->post('price');
if ($price == '3000') {
$price2 = '0';
} else if ($price == '5500') {
$price2 = '3000';
} else if ($price == '6000') {
$price = '10000';
$price2 = '3500';
}
$size = $this->input->post('size');
$type = $this->input->post('type');
$design = $this->input->post('design');
//echo "SELECT * FROM `product_info` WHERE `ac_price` > $price2 AND `ac_price` <= $price AND `design` = '$type' AND `size` = '$size' AND `type` = '$design' GROUP BY `id` ORDER BY `rating` DESC";die;
$filter = $this->queries->custom("SELECT * FROM product_info GROUP BY model ORDER BY model ASC");
if (count($filter) > 99) {
$limits = 99;
} else {
$limits = count($filter);
}
if($this->input->post('more') == 'full'){
$limits = count($filter);
}
if($this->input->post('more') == 'less'){
$limits = 99;
}
{
$rating = "";
for ($a = 0; $a < $limits; $a++) {
$detail_len = (strlen($filter[$a]->detail) > 100) ? '...' : '';
for ($b = 0; $b < $filter[$a]->rating; $b++) {
$rating .= '<span class="fa fa-star"></span>';
}
if ($filter[$a]->rating == 1) {
for ($c = 0; $c < 4; $c++) {
$rating .= '<span style="color: #a2a1a0!important;" class="fa fa-star"></span>';
}
} elseif ($filter[$a]->rating == 2) {
for ($c = 0; $c < 3; $c++) {
$rating .= '<span style="color: #a2a1a0!important;" class="fa fa-star"></span>';
}
} elseif ($filter[$a]->rating == 3) {
for ($c = 0; $c < 2; $c++) {
$rating .= '<span style="color: #a2a1a0!important;" class="fa fa-star"></span>';
}
} elseif ($filter[$a]->rating == 4) {
for ($c = 0; $c < 1; $c++) {
$rating .= '<span style="color: #a2a1a0!important;" class="fa fa-star"></span>';
}
}
echo '
<div class="col-md-4 get_attr" model="' . $filter[$a]->model . '" brand="' . $filter[$a]->brand . '" >
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
</div>
<div class="col-md-12 best">
<div class="col-md-12 best-img text-center">
<img src="' . base_url() . 'uploads/' . $filter[$a]->pic . '" alt="brand-one" style="height: 180px;">
<div class="flipdiv">
<div class="rating col-md-12 text-center nopad">
' . $rating . '
</div>
</div>
<!-- Rating -->
<!-- Modal -->
</div>
<div class="col-md-12 best-detail">
<table class="table table-bordered">
<tr>
<td style="display:none;">' . $filter[$a]->brand . '</td>
<td style="display:none;">' . $filter[$a]->model . '</td>
<td style="display:none;">' . $filter[$a]->ac_price . '</td>
<td style="display:none;">' . $filter[$a]->ram . '</td>
<td style="display:none;">' . $filter[$a]->processor . '</td>
<td style="display:none;">' . $filter[$a]->size . '</td>
<td style="display:none;">' . $filter[$a]->network . '</td>
<td style="display:none;">' . $filter[$a]->pic . '</td>
<td style="display:none;">' . $filter[$a]->detail . '</td>
<td> Mærke </td>
<td id="brand" style="display:none;" class="text-right">' . $filter[0]->brand . '</td>
<td class="text-right">' . $filter[$a]->brand . '</td>
</tr>
<tr>
<td> Model </td>
<td id="model" style="display:none;" class="text-right">' . $filter[0]->model . '</td>
<td class="text-right">' . $filter[$a]->model . '</td>
</tr>
<tr>
<td>Pris</td>
<td class="text-right">' . $filter[$a]->ac_price . ',00 kr.</td>
</tr>
<tr>
<td style="vertical-align:middle!important; height:100px!important; line-height:25px!important;" colspan="2" class="text-center">' . substr($filter[$a]->detail, 0, 100) . ' ' . $detail_len . '</td>
</tr>
</table>
</div>
<div class="text-center">
<button class="btn btn-success btn-sm view_detail form-control"> Mere Information </button>
</div>
</div>
</div>
</div>
</div>
';
$rating = "";
}
}
}
in my index.php file i've written this:
<section>
<div class="col-md-12">
<form>
<select name="users" onchange="showBrand(this.value)">
<option value="">Vælg Mærke:</option>
<option value="1">Samsung</option>
<option value="2">Apple</option>
<option value="3">Huawei</option>
<option value="4">Sony</option>
</select>
</form>
</div>
</section>
<script>
/* Initial Filters */
$(document).ready(function () {
$('.loader_div').fadeIn();
var type = $('.type').val();
var price = $('.price').val() ;
var size = $('.ram').val();
var design = $('.design').val();
$.post('<?php echo base_url(); ?>mobiler/home/filter',function(data) {
if (data == '') {
$('.search_section').show();
$('.no_result').show();
}
$('#filter_list').html(data);
var brand = $('.get_attr').eq(0).attr('brand');
var model = $('.get_attr').eq(0).attr('model');
/* Sorting Bar */
function showBrand(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","<?php echo base_url(); ?>mobiler/home/showBrand"+str,true);
xmlhttp.send();
}
}
</script>
The Jquery scripts are also active, as they are used on other parts of the site.
I know this is very bad formulated question, and a rather a cry for programming help, than an actual answer, and i'm sorry for that, but after two days with no progress what so ever, I have to try this.
I would like to sort after 'brand' btw.
This is my order list sortOrder.php:
<?php
$queryMain ="SELECT newsvid.id, newsvid.addName, newsvid.vidTitle, newsvid.vidType, newsvid.size, newsvid.url, newsvid.vidSD, newsvid.published, videoinformation.vidLD, videoinformation.vidYear, videoinformation.vidCity, videoinformation.vidZanr, videoinformation.vidZanr2, videoinformation.vidZanr3, videoinformation.vidQuality, videoinformation.vidTranslated, videoinformation.vidTime FROM newsvid, videoinformation WHERE newsvid.id = videoinformation.id AND approved='1'";
// Video type
$vType = isset($_GET['vType']) ? $_GET['vType'] : 'ALL';
$goodTypeParam = array("AnyType", "Film", "Serials", "Cartoon", "Anime");
if (in_array($vType, $goodTypeParam)) {
if($vType == 'AnyType'){}
else{$queryMain .= " AND newsvid.vidType ='".$_GET['vType']."'";}
}
//Video Genre one
$vGenre = isset($_GET['vGenre']) ? $_GET['vGenre'] : 'ALL';
$goodGenreParam = array("AnyGenre1", "Action", "Adventure", "Comedy", "Crime", "Faction", "Fantasy", "Historical", "Horror", "Mystery", "Paranoid", "Philosophical", "Political", "Realistic", "Romance", "Saga", "Satire", "Science-Fiction", "Slice-Of-Life", "Speculative", "Anime");
if (in_array($vGenre, $goodGenreParam)) {
if($vGenre == 'AnyGenre1'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre']."')";}
}
//Video Genre two
$vGenre2 = isset($_GET['vGenre2']) ? $_GET['vGenre2'] : 'ALL';
$goodGenre2Param = array("AnyGenre2", "Action2", "Adventure2", "Comedy2", "Crime2", "Faction2", "Fantasy2", "Historical2", "Horror2", "Mystery2", "Paranoid2", "Philosophical2", "Political2", "Realistic2", "Romance2", "Saga2", "Satire2", "Science-Fiction2", "Slice-Of-Life2", "Speculative2", "Anime2");
if (in_array(vGenre2, $goodGenre2Param)) {
if(vGenre2 == 'AnyGenre2'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre2']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre2']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre2']."')";}
}
//Video Genre three
$vGenre3 = isset($_GET['vGenre3']) ? $_GET['vGenre3'] : 'ALL';
$goodGenre3Param = array("AnyGenre3", "Action", "Adventure", "Comedy", "Crime", "Faction", "Fantasy", "Historical", "Horror", "Mystery", "Paranoid", "Philosophical", "Political", "Realistic", "Romance", "Saga", "Satire", "Science-Fiction", "Slice-Of-Life", "Speculative", "Anime");
if (in_array($vGenre, $goodGenre3Param)) {
if($vGenre3 == 'AnyGenre3'){}
else{$queryMain .= " AND ( videoinformation.vidZanr ='".$_GET['vGenre3']."' OR videoinformation.vidZanr2 ='".$_GET['vGenre3']."' OR videoinformation.vidZanr3 ='".$_GET['vGenre3']."')";}
}
// Video Years
$vYear = isset($_GET['vYear']) ? $_GET['vYear'] : 'ALL';
$goodYearParam = array("AnyYear", "2014", "2013", "2012", "2011", "2010", "2009", "2008", "2007", "2006", "2005", "2004", "2003", "2002", "2001", "2000", "1999", "1998", "1997");
if (in_array($vType, $goodYearParam)) {
if($vYear == 'AnyYear'){}
else{$queryMain .= " AND newsvid.vidYear ='".$_GET['vYear']."'";}
}
// Video City
$vCity = isset($_GET['vCity']) ? $_GET['vCity'] : 'ALL';
$goodCityParam = array("AnyCity", "Russian", "England");
if (in_array($vCity, $goodCityParam)) {
if($vCity == 'AnyCity'){}
else{$queryMain .= " AND newsvid.vidCity ='".$_GET['vCity']."'";}
}
//NEW of OLD
$order = isset($_GET['order']) ? $_GET['order'] : 'ALL';
$goodParam = array("NEW", "OLD");
if (in_array($order, $goodParam)) {
if($order == 'NEW'){
$queryMain .= " ORDER BY newsvid.id ASC";
}else if($order == 'OLD'){
$queryMain .= " ORDER BY newsvid.id DESC";
}else{
$queryMain .= " AND videoinformation.vidYear = 2014";
}
}
?>
And this is main page view.php:
<!DOCTYPE lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<?php include 'BSH.php' ?>
<link rel="stylesheet" type="text/css" href="CSS/sdvid.css">
<title><?php echo $lang['PAGE_TITLE_MAIN'] ?></title>
</head>
<body>
<?php
include_once 'userPages/check_login_status.php';
include_once 'incIndex/headerTop.php';
include 'connect/con.php';
include_once 'inc/sortOrder.php';
?>
<?php
$sqlPages = "SELECT COUNT(id) FROM newsvid WHERE approved='1'";
$queryPages = mysqli_query($con, $sqlPages);
$row = mysqli_fetch_row($queryPages);
// Here we have the total row count
$rows = $row[0];
// This is the number of results we want displayed per page
$page_rows = 1;
// This tells us the page number of our last page
$last = ceil($rows/$page_rows);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Establish the $pagenum variable
$pagenum = 1;
// Get pagenum from URL vars if it is present, else it is = 1
if(isset($_GET['pn'])){
$pagenum = preg_replace('#[^0-9]#', '', $_GET['pn']);
}
// This makes sure the page number isn't below 1, or more than our $last page
if ($pagenum < 1) {
$pagenum = 1;
} else if ($pagenum > $last) {
$pagenum = $last;
}
// This sets the range of rows to query for the chosen $pagenum
$limit = "LIMIT " .($pagenum - 1) * $page_rows ."," .$page_rows;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$queryMainList = $queryMain . $limit;
$resultDisplay = mysqli_query($con, $queryMainList);
// This shows the user what page they are on, and the total number of pages
$pagesTitle = "On website <b>$rows</b>";
$pagesOutOf = "Page <b>$pagenum</b> of <b>$last</b>";
// Establish the $paginationCtrls variable
$paginationCtrls = '';
// If there is more than 1 page worth of results
if($last != 1){
/* First we check if we are on page one. If we are then we don't need a link to
the previous page or the first page so we do nothing. If we aren't then we
generate links to the first page, and to the previous page. */
if ($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= 'Previous ';
// Render clickable number links that should appear on the left of the target page number
for($i = $pagenum-4; $i < $pagenum; $i++){
if($i > 0){
$paginationCtrls .= ''.$i.' ';
}
}
}
// Render the target page number, but without it being a link
$paginationCtrls .= ''.$pagenum.' ';
// Render clickable number links that should appear on the right of the target page number
for($i = $pagenum+1; $i <= $last; $i++){
$paginationCtrls .= ''.$i.' ';
if($i >= $pagenum+4){
break;
}
}
// This does the same as above, only checking if we are on the last page, and then generating the "Next"
if ($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' Next ';
}
}
$list = '';
while($row = mysqli_fetch_array($resultDisplay, MYSQLI_ASSOC)){
$list .= "<div class=\"panel-heading\">
<div><a class=\"panel-title btn-block\" href=\"details.php?id=".$row['id']."\"><h3>".$row['id']." | ".$row['vidTitle']."</h3></a></div>
</div>
<div class=\"panel-body\">
<div class=\"imgCover\"><img class=\"imageCover\"src=\"" . $row['url'] . "\"></div>
<div class=\"vidSD\">" . $row['vidSD'] . "</div>
<div class=\"vidDetails\">
<hr class=\"style-two\">
<table>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtYear'] . "</strong></td><td class=\"vidDetailsTD\">" . $row['vidYear'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtCity'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidCity'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtGenre'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidZanr'] ." , ". $row['vidZanr2'] ." , ". $row['vidZanr3'] . "</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtQuality'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidQuality'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtTranslatedBy'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidTranslated'] ."</td></tr>
<tr><td class=\"vidDetailsTD\"><strong>" . $lang['vtVideoTime'] . "</strong></td><td class=\"vidDetailsTD\">". $row['vidTime'] . "</td></tr>
</table>
</div></div>
<div class=\"panel-footer\">
<h6><strong>" . $lang['vsdAuthor'] . "</strong>".$row['addName']."</h6>
<div><h6><strong>" . $lang['vsdPublished'] . "</strong>" . $row['published'] . "</h6></div>
</div>";
}
mysqli_close($con);
?>
<div class="mainLeftCover">
<form action="view.php" method="GET">
<div class="input-group" style="width:180px">
<span class="input-group-addon" style="width:65px"><?php echo $lang['vidOrderTitleNew'] ?></span>
<select class="form-control" name = "order">
<option value="NEW">NEW</option>
<option value="OLD">OLD</option>
</select>
</div>
<?php
include_once 'inc/sortInc/sortType.php';
include_once 'inc/sortInc/sortGenre.php';
include_once 'inc/sortInc/sortGenre2.php';
include_once 'inc/sortInc/sortGenre3.php';
include_once 'inc/sortInc/sortYear.php';
include_once 'inc/sortInc/sortCity.php';
?>
<br><button type="submit" class="btn btn-default" style="width:180px">Submit</button>
</form>
<?php echo" <div id=\"pagination_controls\">" .$paginationCtrls. "</div>"; ?>
</div>
<?php
echo "<div class=\"maincover \" data-role=\"scrollbox\" data-scroll=\"vertical\">";
echo "<div class=\"panel panel-default\">";
echo" <div style=\"background-color:#fff\">" .$list. "</div>";
echo "</div></div>";
?>
Just for encase I gave full code. The problem is, that PAGINATION on it's own working fine... And ORDER function working fine separately as well. BUT TOGETHER they do not want to work. As result I have working pagination and if try to use sort it's just become empty page.
What I need..is somehow make sorting method working with pagination together, but i'm stuck how to do it.
I have this url when I'm using pagination:
http://example.net/view.php?pn=3
And this one when I'm using order:
http://example.net/view.php?order=NEW&vType=Film&vGenre=AnyGenre1&vGenre2=AnyGenre2&vGenre3=AnyGenre3&vYear=AnyYear&vCity=AnyCity
AND I need that URL will be like this:
http://example.net/view.php?pn=3&order=NEW&vType=Film&vGenre=AnyGenre1&vGenre2=AnyGenre2&vGenre3=AnyGenre3&vYear=AnyYear&vCity=AnyCity
That if you sort the page... it will remember how user was sort the list and open pages (pn=1, pn=2) will change.
May be some how save sort result and then use it in pagination..need to save it maybe when submit button pressed? But how can I save result from user???
<?php
session_start();
include_once 'dbconnect.php';
?>
<?php include ('head.php') ; ?>
<?php include ('menu.php') ; ?>
<?php if (isset($_SESSION['usr_id'])) { ?>
<?
$per_page = 15;
if (isset($_GET["page"])) {$page = $_GET["page"];}else {$page = 1;}
if (isset($_GET["order"])) {$order = $_GET["order"];}else {$order = username;}
$start_from = ($page-1) * $per_page;
if(isset($_GET['order']) && $_GET['order'] == 'user_id'){
$query = "select * from users order by user_id DESC limit $start_from, $per_page";}
if(isset($_GET['order']) && $_GET['order'] == 'username'){
$query = "select * from users order by username ASC limit $start_from, $per_page";}
if(isset($_GET['order']) && $_GET['order'] == 'posts'){
$query = "select * from users order by posts DESC limit $start_from, $per_page";}
$result = mysqli_query ($DBcon, $query);
$user_list_result = $DBcon->query("select * from users order by $order ASC limit 100");
$session = $_SESSION['usr_name'];
$query = $DBcon->query("SELECT * FROM users WHERE username='$session'");
$userRow=$query->fetch_array();
if ($userRow['userlevel'] > 0) {
?>
<div class="container">
<div class="row">
<div class="col-lg-6 col-sm-12">
<div class="panel panel-default panel-compact panel-wallet">
<div class="panel-body">
<center><h1>Userlist </h1></center>
<center>
<table >
<tr> <td width="20%"><b>ID </b></td>
<td width="20%"><b>Nickname </b></td>
<td width="20%"><b>Posts </b></td>
<td width="20%"><b>Message </b></td>
<td width="20%"><b>Click </b></td> </tr>
<?php
while($UserlistRow = $result->fetch_array())
{
echo "
<tr>
<td>$UserlistRow[user_id]</td>
<td><a href=user_profile.php?user=$UserlistRow[username]>$UserlistRow[username]</a></td>
<td>$UserlistRow[posts]</td>
</center>
<td><a href=msg_send.php?to=$UserlistRow[username]>Send Message</a></td>
<td><a href=user_click.php?to=$UserlistRow[username]>Click</a></td> ";?>
</tr>
<?php } ?> </table>
</center>
<?
$query = "select * from users order by $order";
$result = mysqli_query($DBcon, $query);
$total_records = mysqli_num_rows($result);
$total_pages = ceil($total_records / $per_page);
echo "<a href='user_list.php?page=" . ($_GET['page']+1) . "&order=" . ($_GET['order']) . "'>Next Page</a>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='user_list.php?page=".$i."&order=" . ($_GET['order']) . "'>".$i."</a> ";
};
echo "<a href='user_list.php?page=" . ($_GET['page']-1) . "&order=" . ($_GET['order']) . "'>Previous Page</a>";
?>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<?php } else { include('login_frame.php'); } ?>
<?php include ('footer.php') ; ?>
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm really tired of making "if elseif else" statements do you know a fun way to deal with this :
For the purpose of this example I'll focused on 3 variables but in reallity there are more than 500.
Required variables :
name
Those variables can be empty :
birthdate, city
I want to write a sentence like that :
The user John Doe who is 35 aged and leave in Pittsburg.
But if the birthdate is empty I want to write :
The user John Doe leave in Pittsburg.
And so on....
You can see the expected output and the real array of values here :
http://jsfiddle.net/CMC8a/1/
I tried multiple ways to approach this issue see more here :
<style>
*{
font-family: Helvetica;
}
label{
font-size: large;
}
</style>
<table id="entete">
</table>
<h2><?php echo $data['patient']['nom']['value'] ?> <?php echo $data['patient']['prenom']['value'] ?> <?php echo age_count($data['patient']['ddn']['value']) ?> ans</h2>
<?php
$blocInfoGenerales = new BlocColumnPdf(
'Informations générales', array(
$data['patient']['ddn'],
$data['patient']['sexe'],
$data['patient']['profession'],
$data['patient']['villeNaissance']
, $data['patient']['departement'])
, 2
);
$blocInfoGenerales->render();
?>
<h3>Antécédents personnels</h3>
<table>
<tr>
<td><label>Respiratoires : </label><?php echo makeCommaForThoseMCB(array($data['N1']['asthme'], $data['N1']['rhinite'], $data['N1']['bcpo'], $data['N1']['insuffisanceResp'], $data['N1']['chirurgieOrl'], $data['N1']['autreChirurgie'], $data['N1']['allergies'], $data['N1']['old'])) ?></td>
</tr>
<tr>
<td><label>Cardio-vasculaires et cérébraux : </label><?php echo makeCommaForThoseMCB(array($data['N1']['hypertensionArterielle'], $data['N1']['infarctusMyocarde'], $data['N1']['bcpo'], $data['N1']['insuffisanceCoronaire'], $data['N1']['troubleRythme'], $data['N1']['accidentVasculaireCerebral'], $data['N1']['insuffisanceCardiaque'], $data['N1']['arteriopathie'])) ?></td>
</tr>
<tr>
<td><label>Autres : </label><?php echo makeCommaForThoseMCB(array($data['N1']['tabagismeActuel'], $data['N1']['tabagismeAncien'], $data['N1']['alcool'], $data['N1']['refluxGastro'], $data['N1']['glaucome'], $data['N1']['diabete'], $data['N1']['hypercholesterolemie'], $data['N1']['hypertriglyceridemie'], $data['N1']['dysthyroidie'], $data['N1']['depression'])) ?></td>
</tr>
<tr>
<td><label>Antécédents familiaux : </label><?php echo makeCommaForThoseMCB(array($data['N1']['sedentarite'], $data['N1']['syndromeDApneesSommeil'], $data['N1']['obesite'], $data['N1']['dysmorphieFaciale'])) ?></td>
</tr>
</table>
<h3>Traitements en cours</h3>
<table>
<tr>
<td><?php echo makeCommaforThisVMB($data['N1']['vidalMultiBox'], 'vidalMultiBox') ?></td>
</tr>
</table>
<h3>Première visite</h3>
<table>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['dateVisite'], $data['suivi1'][0]['adressePar'], $data['suivi1'][0]['selecMedecinSpecialiste'])) ?>
</td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['motifConsultation'])) ?>
</td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['taille'], $data['suivi1'][0]['poids'], $data['suivi1'][0]['perimetreCervical'], $data['suivi1'][0]['perimetreAbdominal'])) ?>
</td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['PASystolique'], $data['suivi1'][0]['PADiastolique'])) ?>
</td>
</tr>
<tr>
<td><label> <?php echo makeCommaForThoseMCB(array($data['suivi1'][0]['profilMaxilofacial'])) ?></label></td>
</tr>
<tr>
<td>
<?php echo makeCommaForThoseFields(array($data['suivi1'][0]['autoPASystolique'], $data['suivi1'][0]['autoPADiastolique'])) ?>
</td>
</tr>
<tr>
<td>
<label>Bilan Biologique :</label>
<?php
echo makeCommaForThoseFields(array(
$data['suivi1'][0]['dateBilan'], $data['suivi1'][0]['glycemie'],
$data['suivi1'][0]['cholesterolemieTotale'], $data['suivi1'][0]['HDL'],
$data['suivi1'][0]['LDL'], $data['suivi1'][0]['triglycerides']
))
?>
</td>
</tr>
<tr>
<td><label>Clinique :</label> <?php
echo makeCommaForThoseMCB(
array(
$data['suivi1'][0]['ronflements'],
$data['suivi1'][0]['somnolenceDiurne'],
$data['suivi1'][0]['somnolenceConduite'],
$data['suivi1'][0]['fatigueMatinale'],
$data['suivi1'][0]['cephaleesMatinales'],
$data['suivi1'][0]['troubleLibido'],
$data['suivi1'][0]['troubleMemoire'],
$data['suivi1'][0]['troubleErection'],
$data['suivi1'][0]['transpirationNocturne']
))
?>
</td>
</tr>
<tr>
<td><label>Auto-questionnaires :</label> <?php
echo makeCommaForThoseFields(
array(
$data['suivi1'][0]['echelleEpworth'],
$data['suivi1'][0]['echellePichot'],
$data['suivi1'][0]['echelleDepression'],
$data['suivi1'][0]['SJSRCriteresDiagnostiques']
))
?>
</td>
</tr>
<tr>
<?php $data['suivi1'][0]['estimationDureeMoyenneDeSommeil']['label'] = 'Estimation durée moyenne de sommeil' ?>
<td><?php echo makeCommaForThoseFields(array($data['suivi1'][0]['estimationDureeMoyenneDeSommeil'] )) ?></td>
</tr>
<tr>
<td>
<label>Exploration fonctionnelle respiratoire :</label>
<?php
echo makeCommaForThoseFields(array(
$data['suivi1'][0]['dateBilan'], $data['suivi1'][0]['glycemie'],
$data['suivi1'][0]['cholesterolemieTotale'], $data['suivi1'][0]['HDL'],
$data['suivi1'][0]['LDL'], $data['suivi1'][0]['triglycerides']
))
?>
</td>
</tr>
</table>
<?php
function count_capitals($s) {
return strlen(preg_replace('![^A-Z]+!', '', $s));
}
function custom_strtolower($string) {
if (count_capitals($string) <= 1) {
return strtolower($string);
}
return $string;
}
function makeCommaForThoseFields($elements) {
$i = 0;
$response = false;
foreach ($elements as $element) {
if ($element['value']) {
if ($i == 0) {
$response = '<label>' . $element['label'] . '</label> : ';
$response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
$response .= (isset($element['unit'])&& $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
} else {
if ($element['label'] != 'Préciser' && $element['label'] != 'Préciser') {
$response .= ', <label>' . custom_strtolower($element['label']) . '</label> : ';
$response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
$response .= (isset($element['unit'])&& $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
} else {
$response .= ' (';
$response .= (isset($element['libelle'])) ? custom_strtolower($element['libelle']) : $element['value'];
$response .= (isset($element['unit']) && $element['unit'] != 'NULL') ? ' ' . ($element['unit']) : '';
$response .= ')';
}
}
$i++;
}
}
if ($response) {
$response.='.';
}
return $response;
}
function makeCommaforThisVMB($vidalMultiBox, $key) {
$i = 0;
$response = false;
foreach ($vidalMultiBox as $element) {
$response = $element[$key . '_libelle'] . ' ' . $element[$key . '_val_posologie'] . ' ' . $element[$key . '_id_posologie'] . ', ';
}
if ($response) {
$response = substr($response, 0, -2);
$response.='.';
}
return $response;
}
function makeCommaForThoseMCB($elements) {
$i = 0;
$response = false;
foreach ($elements as $element) {
if ($element['value'] == 1) {
if ($i == 0) {
$response = $element['label'];
} else {
$response.= ', ' . strtolower($element['label']);
}
$i++;
}
}
if ($response) {
$response.='.';
}
return $response;
}
class BlocColumnPdf {
private $m_title;
private $elements;
private $m_colone;
private $m_id;
function __construct($title, $p_elements, $p_colone, $id) {
$this->m_title = $title;
foreach ($p_elements as $e) {
$tmp_e = new ElementColumnPdf($e);
if (!$tmp_e->isEmpty()) {
$this->elements[] = $tmp_e;
}
}
$this->m_colone = $p_colone;
return $this;
}
function render() {
$is_empty = true;
foreach ($this->elements as $e) {
if (!$e->isEmpty()) {
$is_empty = false;
break;
}
}
if (!$is_empty) {
echo '<h3>' . $this->m_title . '</h3>';
echo '<table id="' . $this->m_id . '">';
$lines_elements = array_chunk($this->elements, $this->m_colone);
foreach ($lines_elements as $line_elements) {
$this->renderLine($line_elements);
}
echo '</table>';
}
}
function renderLine($elements) {
foreach ($elements as $e) {
if (!$e->isEmpty()) {
$is_empty = false;
break;
}
}
if (!$is_empty) {
echo '<tr>';
foreach ($elements as $e) {
$e->render();
}
echo '</tr>';
}
}
}
class ElementColumnPdf {
private $element;
function __construct($p_element) {
$this->element = $p_element;
return $this;
}
function render() {
$text = (isset($this->element['libelle']) && $this->element['libelle']) ? $this->element['libelle'] : $this->element['value'];
$unit = (isset($this->element['unit']) && $this->element['unit']) ? $this->element['unit'] : '';
if (!$this->isEmpty()) {
echo '<td><label>' . $this->element['label'] . '</label> <span class="value">' . $text . '</span><span class="unit">' . $unit . '</span></td>';
} else {
echo '<td></td>';
}
}
function isEmpty() {
if ($this->element['value']) {
return false;
}
return true;
}
}
The use and abuse of is because of the tool I'm using to convert HTML to PDF. this tool is doing better with table rather than div
What would you do ?
This is actually a potentially interesting question.
What you need to do, ideally, is create an array of "things" to say about the person, then make a human-readable list of facts.
Something like this could work well:
$things = array();
if( !empty($birthdate)) $things[] = "who is aged ".$birthdate;
if( !empty($city)) $things[] = "lives in ".$city;
Then output it:
echo "The user ".$name;
if( $things) { // check that there are actually things to say
$lastthing = array_pop($things);
if( $things) { // see if there are still things, ie. there were at least two
echo implode(", ",$things);
echo " and ";
}
echo $lastthing;
}
The above structure results in grammatically correct lists, based on the number of items:
A
A and B
A, B and C
A, B, C and D
[and so on]
Currently I've 2 tables and have the datas are dynamic.
I need to add pagination for both tables seperately. I had added paginator using paginator class and it is working fine. But the problem is when I click on the next button of the first table then the contents of both tables are changed in to the next page.
Paginator.php
<?php
// Paginator Class
// error_reporting(E_ALL);
define("QS_VAR", "page"); // the variable name inside the query string (don't use this name inside other links)
define("STR_FWD", "Next>>"); // the string is used for a link (step forward)
define("STR_BWD", "<<Prev"); // the string is used for a link (step backward)
$scriptname = (isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '');
define("SCRIPT_NAME", $scriptname);
$v = (isset($_REQUEST['page_num_rows']) ? (is_numeric($_REQUEST['page_num_rows']) ? $_REQUEST['page_num_rows'] : 5) : 5);
define("NUM_ROWS", $v); // the number of records on each page
class Paginator {
var $sql;
var $result;
var $get_var = QS_VAR;
var $rows_on_page = NUM_ROWS;
var $str_forward = STR_FWD;
var $str_backward = STR_BWD;
var $all_rows;
var $num_rows;
var $page;
var $number_pages;
var $url_name = SCRIPT_NAME;
// constructor
function Paginator() {
}
// sets the current page number
function set_page() {
$this->page = (isset($_REQUEST[$this->get_var]) && $_REQUEST[$this->get_var] != "") ? $_REQUEST[$this->get_var] : 0;
return $this->page;
}
// gets the total number of records
function get_total_rows() {
$tmp_result = mysql_query($this->sql);
$this->all_rows = mysql_num_rows($tmp_result);
mysql_free_result($tmp_result);
return $this->all_rows;
}
// get the totale number of result pages
function get_num_pages() {
$this->number_pages = ceil($this->get_total_rows() / $this->rows_on_page);
return $this->number_pages;
}
// returns the records for the current page
function get_page_result() {
$start = $this->set_page() * $this->rows_on_page;
$page_sql = sprintf("%s LIMIT %s, %s", $this->sql, $start, $this->rows_on_page);
$this->result = mysql_query($page_sql);
return $this->result;
}
// get the number of rows on the current page
function get_page_num_rows() {
$this->num_rows = #mysql_num_rows($this->result);
return $this->num_rows;
}
// free the database result
function free_page_result() {
#mysql_free_result($this->result);
}
function display_row_count() {
$var = $this->get_var;
$url_part1 = $this->url_name . "?";
$url_part2 = "&" . $var . "=0" . $this->rebuild_qs($var);
$select = " Show ";
$select.="<form method=get name=page_num_rows_form action=\"$this->url_name\" >"; // [form used for javascript disabled case] -not working
$select.="<select name=page_num_rows id=page_num_rows onChange=\"window.location='$url_part1'+'page_num_rows='+this.value+'$url_part2'\" >";
$select.="<option value=50 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 50 ? ' selected ' : '') : '') . " >50</option>";
$select.="<option value=100 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 100 ? ' selected ' : '') : '') . " >100</option>";
$select.="<option value=150 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 150 ? ' selected ' : '') : '') . " >150</option>";
$select.="<option value=200 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 200 ? ' selected ' : '') : '') . " >200</option>";
$select.="<option value=500 " . (isset($_REQUEST['page_num_rows']) ? ($_REQUEST['page_num_rows'] == 500 ? ' selected ' : '') : '') . " >500</option>";
$select.="</select>";
$select.="<noscript> <input type=submit value=Go /></noscript>";
$select.="</form>"; // form used for javascript disabled case -- not working
$select.=" per page";
return $select;
}
// function to handle other querystring than the page variable
function rebuild_qs($curr_var) {
if (!empty($_SERVER['QUERY_STRING'])) {
$parts = explode("&", $_SERVER['QUERY_STRING']);
$newParts = array();
foreach ($parts as $val) {
if (stristr($val, $curr_var) == false) {
array_push($newParts, $val);
}
}
if (count($newParts) != 0) {
$qs = "&" . implode("&", $newParts);
} else {
return false;
}
return $qs; // this is your new created query string
} else {
return false;
}
}
// this method will return the navigation links for the conplete recordset
function navigation($separator = " | ", $css_current = "", $back_forward = false) {
$max_links = NUM_LINKS;
$curr_pages = $this->set_page();
$all_pages = $this->get_num_pages() - 1;
$var = $this->get_var;
$navi_string = "";
if (!$back_forward) {
$max_links = ($max_links < 2) ? 2 : $max_links;
}
if ($curr_pages <= $all_pages && $curr_pages >= 0) {
if ($curr_pages > ceil($max_links / 2)) {
$start = ($curr_pages - ceil($max_links / 2) > 0) ? $curr_pages - ceil($max_links / 2) : 1;
$end = $curr_pages + ceil($max_links / 2);
if ($end >= $all_pages) {
$end = $all_pages + 1;
$start = ($all_pages - ($max_links - 1) > 0) ? $all_pages - ($max_links - 1) : 1;
}
} else {
$start = 0;
$end = ($all_pages >= $max_links) ? $max_links : $all_pages + 1;
}
if ($all_pages >= 1) {
$forward = $curr_pages + 1;
$backward = $curr_pages - 1;
$navi_string = ($curr_pages > 0) ? "" . $this->str_first . " " . $this->str_backward . " " : $this->str_first . " " . $this->str_backward . " ";
$navi_string .= ($curr_pages < $all_pages) ? " " . $this->str_forward . "" . " " : " " . $this->str_forward . " ";
}
}
return "<span style='font-size:.7em; padding:3px 3px 4px 3px;'>" . $this->current_page_info() . $navi_string . "</span>";
}
function current_page_info() {
$cur_page = $this->set_page() + 1;
$total_pages = $this->get_num_pages();
// $page_info = " Page " . $cur_page . " of " . $total_pages . " ";
// return $page_info;
}
function show_go_to_page() {
$cur_page = $this->set_page() + 1;
$total_pages = $this->get_num_pages();
$options = "";
for ($i = 1; $i <= $total_pages; $i++) {
$options.="<option value=$i " . (($i == $cur_page) ? ' selected ' : '') . ">$i</option>";
}
$page_info = " Go to page <input type=text name=paginator_go_to_page id=paginator_go_to_page size=1 value=$cur_page />";
// $page_info.= "<select name=paginator_go_to_page2 >$options</select>";
return $page_info;
}
}
?>
tables.php
<?php
include("library/paginator.php");
?>
<div style="text-align:right;">
<?
$query = "select * from haves_settings";
$tab = mysql_query($query);
$row = mysql_fetch_array($tab);
$item_no = $row['items_to_show'];
$scroll = $row['scroll_interval'];
$online_paginate = new Paginator;
$online_paginate->sql = "select * from placing_item_bid where status='Active' and picture1!='' and selling_method!='want_it_now' and selling_method!='ads' and bid_starting_date <= now() and expire_date>=now() order by item_id desc"; // sql statement
$online_paginate->rows_on_page = $item_no;
$results = $online_paginate->get_page_result(); // result set
$num_rows = $online_paginate->get_page_num_rows(); // number of records in result set
$nav_links = $online_paginate->navigation(" | "); // the navigation links (define a CSS class
?>
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#d79196" class="detail9txt">
<input type="hidden" value="2" name="len">
<td align="center" width="20%"><b>Picture</b> </td>
<td width="30%" align="center"><b>Name / Responses</b> </td>
<td width="50%" align="center"><b>Description</b> </td>
</tr><tr style="height:10px;"><td></td></tr>
<?
if ($num_rows > 0) {
while ($bestsellers_fetch = mysql_fetch_array($results)) {
$temp = $bestsellers_fetch['item_id'];
$sql = "SELECT count(`user_id`) as response FROM `watch_list` where `item_id`=$temp group by `item_id`";
$res = mysql_query($sql);
$response = mysql_fetch_row($res);
$counttop = $counttop + 1;
if (!empty($bestsellers_fetch['sub_title']))
$item_subtitle1 = $bestsellers_fetch['sub_title'];
else
$item_subtitle1 = substr($bestsellers_fetch['item_title'], 0, 20);
$item_title1 = substr($bestsellers_fetch['item_title'], 0, 40)
?>
<tr>
<td class="tr_botborder" style="vertical-align:middle;" width="20%" align="center"><div align="center"><img src="thumbnail/<?= $bestsellers_fetch['picture1']; ?>" alt="" width="79" height="70" border="0" /></div></td>
<td class="tr_botborder" style="vertical-align:middle;" width="30%" align="center"><div align="center"><span class="bestsellerstxt"><?= $item_subtitle1; ?> <?= $item_title1; ?><br/><?php if ($response[0] != '') { ?><a style="text-decoration:none;color:#336666;" href="detail.php?item_id=<?= $bestsellers_fetch['item_id']; ?>"> <?php echo $response[0] . ' responses'; ?></a> <?php } else { ?><span style="color:#666666;"><?php
echo '0 responses';
}
?></span></span></td>
<td class="tr_botborder" style="vertical-align:middle;" width="50%" align="center"><div align="center"><span class="bestsellerstxt"><?= html_entity_decode($bestsellers_fetch['detailed_descrip']); ?></span></td>
</tr>
<?
if ($counttop != 2) {
}
}
} else {
?>
<tr><td height="148" align="center" class="featxt">No Items Available</td></tr>
<?
}
?>
</table>
<div style="text-align: right;"><?php echo $nav_links; ?></div>
//wants content
$online_paginate1 = new Paginator;
$online_paginate1->sql = "select * from placing_item_bid where status='Active' and selling_method='want_it_now' order by item_id desc";
$online_paginate1->rows_on_page = $item_no1;
$result1 = $online_paginate1->get_page_result(); // result set
$want_total_records = $online_paginate1->get_page_num_rows(); // number of records in result set
$nav_links1 = $online_paginate1->navigation(" | "); // the navigation links (define a CSS class
?>
<div class="superbg">
<table cellspacing="0" cellpadding="5" width=100%>
<form name="want_form" action="myauction.php" method=post>
<tr bgcolor="#d79196" class="detail9txt">
<input type="hidden" name="len" value="<?= $want_total_records ?>">
<td align="center" width="30%"><b>Name / Responses</b> </td>
<td align="center" width="20%"><b>Picture</b> </td>
<td width="50%" align="center"><b>Description</b> </td>
</tr>
<?
if ($want_total_records > 0) {
while ($want_row = mysql_fetch_array($result1)) {
$tot_bid_sql = "select count(*) from want_it_now where wanted_itemid=" . $want_row[item_id];
$tot_bid_res = mysql_query($tot_bid_sql);
$tot_bids = mysql_fetch_array($tot_bid_res);
?>
<tr class="detail9txt">
<td class="tr_botborder" align="center" style="vertical-align:middle;" width="30%">
<a href="wantitnowdes.php?item_id=<?= $want_row['item_id'] ?>" class="header_text">
<? echo $want_row['item_title']; ?></a> <br/> <?
if ($tot_bids[0] != 0) {
?>
<a style="font-weight:normal;" href="wantitnowdes.php?item_id=<?= $want_row['item_id'] ?> " class="header_text"><? echo $tot_bids[0] . ' responses'; ?></a>
<?
} else {
echo $tot_bids[0] . ' responses';
}
?></td>
<td class="tr_botborder" style="vertical-align:middle;" width="20%" align="center">
<?
if (!empty($want_row['picture1'])) {
$img = $want_row['picture1'];
list($width, $height, $type, $attr) = getimagesize("images/$img");
$h = $height;
$w = $width;
if ($h > 50) {
$nh = 50;
$nw = ($w / $h) * $nh;
$h = $nh;
$w = $nw;
}
if ($w > 50) {
$nw = 50;
$nh = ($h / $w) * $nw;
$h = $nh;
$w = $nw;
}
?>
<!-- <img name="runimg" src="images/<? //echo $want_row['picture1']; ?>" border=1 width=<? //= $w; ?> height=<? //=$h ?> >-->
<img name="runimg" src="images/<? echo $want_row['picture1']; ?>" border=1 width="79" height="70" >
<?
} else {
?>
<img src="images/no_image.gif" border=1 name="runimg" >
<? } ?>
</td>
<td class="tr_botborder" style="vertical-align:middle;" width="50%" align="center"><div align="center"><span class="bestsellerstxt"><?= html_entity_decode($want_row['detailed_descrip']); ?></span></td>
</tr>
<?
} // while
} else {
?>
<tr>
<td width="3%"> </td>
<td width="97%" class="myauction3txt">There are no items in this section</td>
</tr>
<? } ?>
</table>
<div style="text-align: right;"><?php echo $nav_links1; ?></div>
</div>
Where is the problem ?
Paginator class uses the same query string "page" parameter to calculate the current page. If you add 2 or more Pagination in the same request, "page" will be shared by all instances, leading to this mess you described.
How to fix it ?
Tell the Paginator class which parameter to use in query string... follow this 2-step patch below :
Step 1 : replace constructor in Paginator class
// constructor
function Paginator($get_var=null) {
if ($get_var!=null) $this->get_var = $get_var;
}
Step 2 : update Paginator object creation (twice)
$online_paginate = new Paginator('page_table1');
and later :
$online_paginate1 = new Paginator('page_table2');
Hope this helps !