Insert archive loop insert another page - php

I have archive.php in my content management system which allows to search for articles like mywebsite.com/archive?s=test. Now i tried to show this posts of the search query in another page of my page. Like <?php insert('archive.php?s=test'); ?> .
I am not an expert on PHP coding. But maybe you can show me a way how i could import this post of a search query with archive.php loop. Or tell me that this is not possible :-) Thank you.
This is the code my archive page.
<?php if (!$t['page_heading']) : ?>
<?php endif; ?>
<?php if (has_items($t['latest_posts'])) : ?>
<div class="row">
<?php foreach ($t['latest_posts'] as $t['loop']) : ?>
<div class="col-12 mb-3">
<?php insert('partials/loop.php'); ?>
</div>
<?php endforeach; ?>
</div> </div> </div>
<?= $t['pagination_html']; ?>
<?php else : ?>
<?php
insert(
'partials/empty.php',
[
'empty_message' => __('nothing-found-archive', _T)
]
);
?>
<?php endif; ?>
This is the loop.php
<?= e(limit_string($t['loop.post_title'], 65), false); ?>
</h3></a>
<div class="post-footer text-muted">
<div id="hidden-xs"> <?= e(limit_string($t['loop.post_excerpt'], 145), false); ?></div>
<div class="mb-1 mt-1"> <span class="badge badge-cat"><i class="fas fa-newspaper"></i> <?= e_attr($t['loop.feed_name']) ?></span> <span class="badge badge-cat"><i class="far fa-folder-open"></i> <?= e_attr($t['loop.category_name']) ?></span>
<span class="badge badge-cat"><i class="far fa-clock"></i> vor <?= time_ago($t['loop.post_pubdate'], _T); ?></span>
search function
public function archive()
{
$app = app();
$postModel = new PostModel;
$feedModel = new FeedModel;
$engineModel = new EngineModel;
$categoryModel = new CategoryModel;
$data = [
'title' => __('archive', _T),
'meta.description' => __('archive-description', _T),
'body_class' => 'archive',
'searching_site' => false,
'by_feed' => false,
];
$query = sp_strip_tags(trim($app->request->get('s')), true);
$feedID = (int) $app->request->get('feed', 0);
$feedsTable = $feedModel->getTable();
$postsTable = $postModel->getTable();
$categoriesTable = $categoryModel->getTable();
// Current page number
$currentPage = (int) $app->request->get('page', 1);
$filters['sort'] = 'post-publish-date';
if (mb_strlen($query) > 3) {
$filters['where'][] = ["{$postsTable}.post_title", 'LIKE', "%$query%"];
$filters['where'][] = ["{$postsTable}.post_content", 'LIKE', "%$query%", 'OR'];
$data['site_search_query'] = $query;
$data['searching_site'] = true;
$data['page_heading'] = sprintf(__('search-results-for', _T), $query);
$data['title'] = sprintf(__('search-results-for-title', _T), $query);
$data['meta.description'] = sprintf(__('search-results-for-desc', _T), $query);
$data['body_class'] .= ' search-results';
}
if ($feedID) {
$feed = $feedModel->read($feedID, ['feed_id', 'feed_name']);
if ($feed) {
$filters['where'][] = ["{$postsTable}.post_feed_id", '=', $feed['feed_id']];
$data['by_feed'] = true;
$data['feed'] = $feed;
$data['title'] = $feed['feed_name'];
$data['page_heading'] = $feed['feed_name'];
}
}
$itemsPerPage = (int) get_option('latest_posts_count', 10);
// Total item count
$totalCount = $postModel->countRows(null, $filters);
$pageQuery = [];
if ($data['searching_site']) {
$pageQuery['s'] = $query;
}
if ($data['by_feed']) {
$pageQuery['feed'] = $feedID;
}
$queryStr = http_build_query($pageQuery);
if (!empty($queryStr)) {
$queryStr = "&{$queryStr}";
}
// Pagination instance
$pagination = new Pagination($totalCount, $currentPage, $itemsPerPage);
$pagination->setUrl("?page=#id#{$queryStr}");
// Generated HTML
$paginationHtml = $pagination->renderHtml();
// Offset value based on current page
$offset = $pagination->offset();
// Fields to query
$fields[] = "{$postsTable}.post_id, {$postsTable}.post_category_id, {$postsTable}.post_title, {$postsTable}.post_excerpt, {$postsTable}.post_featured_image, {$postsTable}.post_type, {$postsTable}.post_source, {$postsTable}.post_pubdate, {$postsTable}.created_at, {$postsTable}.post_hits";
$fields[] = "{$feedsTable}.feed_name, {$feedsTable}.feed_id, {$feedsTable}.feed_logo_url";
$fields[] = "{$categoriesTable}.category_name, {$categoriesTable}.category_slug, {$categoriesTable}.category_icon";
// Query to fetch the users and their respective role names
$sql = $postModel->select($fields)
->leftJoin(
$feedsTable,
"{$postsTable}.post_feed_id",
'=',
"{$feedsTable}.feed_id"
)->leftJoin(
$categoriesTable,
"{$postsTable}.post_category_id",
'=',
"{$categoriesTable}.category_id"
)->limit($itemsPerPage, $offset);
// Apply Filters
$sql = $postModel->applyModelFilters($sql, $filters);
$stmt = $sql->execute();
// List entries
$latestPosts = $stmt->fetchAll();
$maxSliderItems = get_option('max_slider_items', 10);
$sliderPosts = array_slice($latestPosts, 0, $maxSliderItems);
$engines = $engineModel->readMany(['engine_id', 'engine_name']);
$data['default_engine'] = (int) get_option('default_engine');
$data['engines'] = $engines;
$data['archive_active'] = 'active';
$data['slider_posts'] = $sliderPosts;
$data['latest_posts'] = $latestPosts;
$data['pagination_html'] = $paginationHtml;
return view('archive.php', $data);
}

Related

Query Join table to sort by menudindex

Here is my query:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
I need to sort it by menuindex so i tried this:
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues JOIN modResource WHERE tmplvarid=107 ORDER BY menuindex DESC");
I'm not familiar at all whith this. Of course it doesn't work. Someone told me to use XPDO but i know nothing about it. Do i miss something? What should i do to make it work ?
Here is the full code :
<?php
$results = $modx->query("SELECT contentid FROM modx_site_tmplvar_contentvalues WHERE tmplvarid=107");
// description tv: 108
// vignette tv: 121
if (!is_object($results)) {
return;
}
$breves = array();
while($r = $results->fetch(PDO::FETCH_COLUMN, 0)){
$breves[] = $r;
}
$queryIn = implode(',' , $breves);
$results_2 = $modx->query("SELECT contentid, tmplvarid, value FROM modx_site_tmplvar_contentvalues WHERE contentid IN ({$queryIn}) AND tmplvarid IN (108, 121)");
if (!is_object($results_2)) {
return;
}
$tvValues = array();
while($v = $results_2->fetch(PDO::FETCH_ASSOC)){
if($v['tmplvarid'] == 108){
$tvValues[$v['contentid']]['desc'] = $v['value'];
} else {
$tvValues[$v['contentid']]['vignette'] = $v['value'];
}
}
$output = "";
foreach ($breves as $res_id) {
$page = $modx->getObject('modResource', $res_id);
$alias = $page->get('alias');
$id = $page->get('id');
$page_title = $page->get('pagetitle');
$description = $tvValues[$res_id]['desc'];
if(!$description || $description == ""){
$description = $page->get('content');
}
$description = strip_tags($description);
$description = mb_strimwidth($description, 0, 150, "...");
$vignette = $tvValues[$res_id]['vignette'];
if($vignette){
$vignette = "/assets/upload/pln/" . $vignette;
} else {
$vignette = "https://www.commune-ploudaniel.fr/assets/templates/pln/default-b7824fcd998f51baf0f0af359a72e760.png";
}
$output .= <<<HTML
<div class="xpro-slider-item">
<div class="xp-news-classic-block">
<div class="xp-hover-image">
</div>
<a class="xp-view-lightbox" href="{$alias}.html" ><i class="fa fa-plus"></i></a>
<img src="{$vignette}" alt="{$alias}" style="width:375px; height:270px; object-fit: cover;"/>
</div>
<div class="xp-news-detail">
<h4>{$id}{$page_title}</h4>
<p>{$description}</p>
<div class='xp-news-footer'></div>
</div>
</div>
</div>
HTML;
$output .= PHP_EOL;
}
return $output;
Try this for MODX:
$q = $modx->newQuery('modTemplateVarResource');
$q->leftJoin('modResource', 'mr', 'mr.id = modTemplateVarResource.contentid');
$q->where(array(
'modTemplateVarResource.tmplvarid' => 107
));
$q->select(array(
'modTemplateVarResource.contentid'
));
$q->sortby('modResource.menuindex', 'DESC');
$q->prepare();
$q->stmt->execute();
$result = $q->stmt->fetch(PDO::FETCH_ASSOC);
print_r($result);

Laravel Product Filter by Price

I have a filter route to filter my products by brand & weight & count and taste and all are working fine but when i want to add a sort filter its not working, i want to sort it by pirce ( Ascending and descending).
here is my codes
Route:
Route::match(['get', 'post'], 'products/filter', [SearchController::class, 'filterall']);
SearchController:
public function filterall(Request $request){
$data = $request->all();
// echo "<pre>"; print_r($data);
$brandUrl = "";
$weightUrl = "";
$countUrl = "";
$tasteUrl = "";
$sortUrl = "";
if(!empty($data['brandFilter'])){
foreach ($data['brandFilter'] as $brand){
if(empty($brandUrl)){
$brandUrl = "&brand=".$brand;
}else{
$brandUrl .= "-".$brand;
}
}
}
if(!empty($data['weightFilter'])){
foreach ($data['weightFilter'] as $weight){
if(empty($weightUrl)){
$weightUrl = "&weight=".$weight;
}else{
$weightUrl .= "-".$weight;
}
}
}
if(!empty($data['countFilter'])){
foreach ($data['countFilter'] as $count){
if(empty($countUrl)){
$countUrl = "&count=".$count;
}else{
$countUrl .= "-".$count;
}
}
}
if(!empty($data['tasteFilter'])){
foreach ($data['tasteFilter'] as $taste){
if(empty($tasteUrl)){
$tasteUrl = "&taste=".$taste;
}else{
$tasteUrl .= "-".$taste;
}
}
}
if(!empty($data['sort'])){
foreach ($data['sort'] as $sort){
if(empty($sortUrl)){
$sortUrl = "&sort=".$sort;
}else{
$sortUrl .= "-".$sort;
}
}
}
$finalUrl = "category/".$data['url_id'].'/'.$data['url_slug']."?".$brandUrl.$weightUrl.$countUrl.$tasteUrl.$sortUrl;
return redirect::to($finalUrl);
}
*** My View Controller ***
public function allCategory(Request $request, $id){
$catt = DB::table('categories')->where('id', $id)->first();
$products = Product::where('category_id', $catt->id)->where('status', '1')
->orderBy('brand_id', 'ASC');
if(!empty($_GET['brand'])){
$brandArray = explode('-', $_GET['brand']);
$products = $products->whereIn('brand_id', $brandArray);
}
if(!empty($_GET['weight'])){
$weightArray = explode('-', $_GET['weight']);
$products = $products->whereIn('product_weight', $weightArray);
}
if(!empty($_GET['count'])){
$countArray = explode('-', $_GET['count']);
$products = $products->whereIn('product_count', $countArray);
}
if(!empty($_GET['taste'])){
$tasteArray = explode(',', $_GET['taste']);
foreach ($tasteArray as $taste){
$products = $products->where('product_taste','LIKE', "%$taste%");
}
if(!empty($_GET['sort'])){
$sortArray = explode('-', $_GET['sort']);
$products = $products->orderBy('selling_price', $sortArray);
}
}
$products = $products->paginate(12);
return view('pages.all_category', compact('products', 'catt'));
}
and this is the view code:
<div class="row" id="search-results">
<div class="col-lg-12 col-md-12">
<div class="toolbar toolbar-products">
<div class="toolbar-sorter sorter">
<label class="sorter-label" for="sort">Sort By</label>
#if(!empty($_GET['sort']))
<?php $sortArray = explode('-', $_GET['sort']) ?>
#endif
<select id="sort" name="sort[]" class="sorter-options" onchange="javascript:this.form.submit();">
<option value="">Select</option>
#if(!empty($_GET['sort']))
<?php $price = $_GET['sort'] ?>
#endif
<option value="ASC" #if(!empty($sortArray) && in_array('ASC', $sortArray)) selected="" #endif>Lowest Price</option>
<option value="DESC" #if(!empty($sortArray) && in_array('DESC', $sortArray)) selected="" #endif>Highest Price</option>
</select>
</div>
</div>
</div>
</div>
im doing this by Form in page.
I think orderBy in front Controller is not working is there other way to sort that?

Retrieve and store values into db from uploaded excel file

I am trying to save the attendance details for each employee into a db from an excel file as a bulk attendance upload , the code below displays Excel Data Imported Succesfully , but does not store values into the db, the line $last_id=$this->mod_common->add_attendence_data($data_user); is not executed , thats why its not working , How to make this line execute ? As this code was written by some other developer i am finding it difficult to understand.
Controller: admin_list.php
function upload_bulk_attendance(){
$data['htmltext'] = $this->mod_common->get_allleaves();
$this->data['maincontent'] = $this->load->view('maincontents/upload_attendance_sheet', $data,true);
$this->load->view('layout', $this->data);
}
function importExcel() {
//$this->mod_common->delete_attendance();
$this->load->library('excel');
//microsoft excel 2007
if(!$objReader = PHPExcel_IOFactory::createReader('Excel5')){
die('Unable to create reader object');
}
//$objReader = PHPExcel_IOFactory::createReader('Excel2007');
//set to read only
$objReader->setReadDataOnly(false);
//load excel file
global $SITE;
if(!$upload_val=$this->admin_init_elements->do_upload_docs('user_attendance',$SITE->client_logo_image_src,false)){
$data['error'] = $this->upload->display_errors();
$this->load->view('maincontents/upload_attendance_sheet', $data,true);
} else {
$file_path = $upload_val['upload_data']['full_path'];
}
$objPHPExcel = $objReader->load($file_path);
$objWorksheet = $objPHPExcel->setActiveSheetIndex(1);
/*---------------------------------------------------------------------------*/
$excelrow = 1;
$from_Date = $objWorksheet->getCellByColumnAndRow(4,1)->getValue();
$to_Date = $objWorksheet->getCellByColumnAndRow(6,1)->getValue();
$total_rows_in_sheet = $objPHPExcel->getActiveSheet()->getHighestRow();
if (PHPExcel_Shared_Date::isDateTime($objPHPExcel->getActiveSheet()->getCell('E1'))) {
$dateValue = PHPExcel_Shared_Date::ExcelToPHP($from_Date);
$from_date = date('Y-m-d',$dateValue);
}
if (PHPExcel_Shared_Date::isDateTime($objPHPExcel->getActiveSheet()->getCell('G1'))) {
$dateValue = PHPExcel_Shared_Date::ExcelToPHP($to_Date);
$to_date = date('Y-m-d',$dateValue);
}
$start = strtotime($from_date);
$end = strtotime($to_date);
$days_between = ceil(abs($end - $start) / 86400);
$excelrow = $excelrow + 2;
$emp_code_id_array = $this->mod_common->get_Details2('pr_users_details',array('userid','emp_code'));
foreach($emp_code_id_array as $e){ $emp_code_id[$e['emp_code']] = $e['userid']; }
do {
$shift_excelrow = ++$excelrow;
/*--------------- Moving row wise for each employees data --------------*/
$emp_code = $objWorksheet->getCellByColumnAndRow(0,$excelrow)->getValue();
$emp_code =($emp_code==null)?0:$emp_code;
if($emp_code<=0) continue;
$emp_code = str_pad($emp_code, 3, '0', STR_PAD_LEFT);
$emp_id =($emp_code_id[$emp_code]==null)?0:$emp_code_id[$emp_code];
$emp_name = $objWorksheet->getCellByColumnAndRow(1,$excelrow)->getValue();
/*--------------- Moving column wise for each days data --------------*/
$col_no=3;
for($i=0;$i<=$days_between;$i++) {
$dt = date('Y-m-d',strtotime($from_date));
$day = date('d', strtotime($dt .' +'.$i.' day'));
$entry[] = $day."|".$objWorksheet->getCellByColumnAndRow($col_no,$shift_excelrow)->getValue();
$col_no++;
}
$present=$objWorksheet->getCellByColumnAndRow(34,$shift_excelrow)->getValue();
$absent=$objWorksheet->getCellByColumnAndRow(35,$shift_excelrow)->getValue();
$total=$objWorksheet->getCellByColumnAndRow(36,$shift_excelrow)->getValue();
if($emp_id!=0){
$emp_id_arr[] = $emp_id;
}
/* CREATING ARRAY FOR DB INSERT */
$data_user['emp_code'] = $emp_code;
$data_user['emp_id'] = $emp_id;
$data_user['name'] = $emp_name;
$data_user['entry'] = implode(",",$entry);
$data_user['from_date'] = $from_date;
$data_user['to_date'] = $to_date;
$data_user['present'] = $present;
$data_user['absent'] = $absent;
$data_user['total'] = $total;
$data_user['current_date'] = date('Y-m-d');
$last_id=$this->mod_common->add_attendence_data($data_user);
//Reset array
$entry=array();
}while($excelrow <=$total_rows_in_sheet);
/*----------------------------------------------------*/
if(count($emp_id_arr)==0){
$emp_id_arr[] = 0;
}
$this->mod_common->save_attendance_notification($last_id,implode(",",$emp_id_arr),$data_user['from_date']);
$this->session->set_flashdata('success', 'Excel Data Imported Succesfully');
redirect(base_url().'admin_list/upload_bulk_attendance');
}//importExcel() END
Model: mod_common.php
function add_attendence_data($datauser) {
$emp_code = str_pad($datauser['emp_code'], 3, '0', STR_PAD_LEFT);
$this->db_replace->select('*');
$this->db_replace->from($this->myTables['attendance']);
$this->db_replace->where('emp_code',$emp_code);
$this->db_replace->where('from_date',$datauser['from_date']);
$query=$this->db_replace->get();
if($query->num_rows() <= 0)
{
$datauser['emp_code'] = $emp_code;
$this->db_replace->insert($this->myTables['attendance'],$datauser);
$instanceid = $this->db_replace->insert_id();
return $instanceid;
} else return false;
}
view : upload_attendance_sheet.php
<section class="content-header">
<h1>
Upload Attendance
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-home"></i> Home</li>
<li> Admin</li>
<li>Attendance</li>
<li class="active">Upload Attendance</li>
</ol>
</section>
<section class="content">
<div class="container-fluid">
<div class="row">
<!-- Thought Day-->
<div class="panel wrapper clearfix m-b-none">
<div class="box-header with-border">
<?php if($bulkUploadMsg!=''){?>
<?php echo $bulkUploadMsg;?>
<?php } ?>
<?php
if($this->session->flashdata('success') == TRUE){
echo $this->session->flashdata('success');
}
?>
<br>
<?php
echo form_open_multipart('admin_list/importExcel', array('method'=>'post','name'=>'uploadUserForm','id'=>'upload_file','class'=>"custom-form"));
?>
Please download attendance upload format by clicking here<br><br>
<table cellpadding="10px" style="background:none;width:100%;" RULES="ROWS">
<thead>
<tr>
<td width="50px;">Upload</td>
<td>:</td>
<td>
<?php echo form_upload(array("required"=>"required","name"=>"user_attendance","id"=>"user_attendance")); ?>
</td>
</tr>
</table>
<h3>Instructions to Upload : </h3>
<ul>
<li>Complete the sheet below and upload to update attendance records of all employees
</li><li>
You may add as many rows as needed - one for each employee
</li><li>Enter the start and end dates in the dd/mm/yyyy format only
</li><li>Only use the legend given to enter primary attendance details - Present at assigned office location-X, Absent without notification-A, On Official Travel-O, Present but not in office location-P, Week Off-W, Holiday-H, Half day working-D
</li><li>Use the following legends for entering Leave Details-<?php echo $htmltext; ?>
</li><li>As good practice, ensure that this sheet is uploaded at approximately the same interval each month
</li></ul><br>
</p>
<br>
<?php
echo form_submit(array('name'=>'submit','value'=>'Upload','class'=>'btn btn-info btn-submit pull-right add'));
echo form_close();
?>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/data-tables/DT_bootstrap.js"></script>
Table : pr_attendance
Please try this way:-
<?php
public function importContacts($id)
{
if(isset($_POST["Import"]))
{
$filename=$_FILES["file"]["name"];
$f_extension = explode('.',$filename);
$f_extension = strtolower(end($f_extension));
if($f_extension == 'csv') // for import CSV file
{
$file_tmp_name=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($file_tmp_name, "r");
$row = array();
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
array_push($row, $emapData);
}
fclose($file);
unset($row[0]);
foreach(array_values($row) as $r){
$data = array(
'gc_group_id' => $id,
'gc_user_id' => $this->session->userdata('userId'),
'gc_name' => #$r[1],
'gc_number' => #$r[0],
'gc_email' => #$r[2],
'gc_added_date' => date('Y-m-d'),
);
$this->user_model->add('groups_contact',$data);
array_push($valid_no, $r[0]);
}
fclose($file);
}
}
if($f_extension == 'xlsx' || $f_extension == 'xls')
{
/* PHPExcel library */
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
require_once APPPATH.'third_party/PHPExcel/IOFactory.php';
$file_tmp_name=$_FILES["file"]["tmp_name"];
try {
$objPHPExcel = PHPExcel_IOFactory::load($file_tmp_name);
} catch(Exception $e) {
die('Error loading file :' . $e->getMessage());
}
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
unset($sheetData[1]);
foreach(array_values($sheetData) as $s){
$data = array(
'gc_group_id' => $id,
'gc_user_id' => $this->session->userdata('userId'),
'gc_name' => #$s[B],
'gc_number' => #$s[A],
'gc_email' => #$s[C],
'gc_added_date' => date('Y-m-d'),
);
$this->user_model->add('groups_contact',$data);
array_push($valid_no, $s[A]);
}
}
$msg = 'Contacts Added Successfully ';
}
}
?>
Let me know please if you find any issues.

Delete function always selects same ID - blog - Codeigniter

So, I have been trying to get this delete function to work now for a while.
At the bottom of the foreach I have a delete function. The funtion itself does work, however it always selects the post id of 1.
View
<div><?php foreach($posts as $post) : ?>
<hr>
<h3><?php echo $post['title']; ?></h3>
<div class="row">
<div class="col-md-3">
<img class="post-thumb" src="<?php echo site_url(); ?>posts/image/<?php echo $post['post_image']; ?>">
</div>
<div class="col-md-9">
<small class="post-date">Posted on: <?php echo $post['created_at']; ?> in <strong><?php echo $post['name']; ?></strong></small><br>
<?php echo word_limiter($post['body'], 60); ?>
<br><br>
<p><a class="btn btn-default" href="<?php echo site_url('/posts/'.$post['slug']); ?>">Read More</a></p>
</div>
</div>
<?php echo form_open('/posts/delete/'.$post['id']); ?>
<input type="submit" value="Delete" class="btn btn-danger">
</form>
Controller
public function posts($offset = 0){
// Pagination Config
$config['base_url'] = base_url() . 'admins/posts/';
$config['total_rows'] = $this->db->count_all('posts');
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['attributes'] = array('class' => 'pagination-link');
// Init Pagination
$this->pagination->initialize($config);
$data['title'] = 'Latest Posts';
$data['posts'] = $this->post_model->get_posts(FALSE, $config['per_page'], $offset);
$this->load->view('templates/header');
$this->load->view('admins/posts', $data);
$this->load->view('templates/footer');
}
Model
public function delete_post($id){
$image_file_name = $this->db->select('post_image')->get_where('posts', array('id' => $id))->row()->post_image;
$cwd = getcwd(); // save the current working directory
$image_file_path = $cwd."\\assets\\images\\posts\\";
chdir($image_file_path);
unlink($image_file_name);
chdir($cwd); // Restore the previous working directory
$this->db->where('id', $id);
$this->db->delete('posts');
return true;
}
EDIT:
get_posts in model
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
The function does run and I get a confirmation message, so the only thing I am really confused about is the Id.
The whole thing is written using the CodeIgniter Framework.
Check your get_post model properly. From what you have, it looks like your query will get it's id from the category table.
Try this instead
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->select('posts.id AS id, posts.slug, posts.body, posts.created_at');
$this->db->from('posts, categories');
$this->db->where('categories.id = posts.category_id');
$query = $this->db->get();
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->result_array();
}
Updating your join to LEFT JOIN or simple use WHERE
you are returning only 1 line with row_array() function so you should replace for result_array():
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit, $offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}else{
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->result_array();
}
}
Thanks to everyone, your answers helped me a lot and I learned a few new things about PHP. I tried implementing your Ideas and they solved the area of the problem I was asking about. In the end I decided to use a simple mysqli query to get the data I needed from the database. mysqli_query($con, "SELECT id,category_id,user_id,title,body,created_at FROM posts Order By id DESC");
May be i am wrong but i think its a foreach syntax issue,
because if you getting same id in all the
rows,
you need to write like,
<?php foreach ($posts as $post) : ?>
instead of,
<?php foreach ($posts as $post) { ?>
//your code goes here
<?php } ?>

codeigniter pagination-result not display at the next page

I have implemented the CI Pagination into the system correctly. i have set limit 25 result per page. but i like to let user to change the limit such as 50,75,100 if they wish. The system work perfectly in first page if the user choose to view 50 result, but when the user click on the next page link or do sort table column, it return to limit 25.
here is my code.
view:
<?php
if(isset($_POST['num']))
{
$selected_option = $_POST['num'] ;
}else{
$selected_option ='';
}
$options = array(25,50,75,100);
?>
<form id="myForm" method="post" action = "">
Show <select name="num" onchange="document.getElementById('myForm').submit()">
<?php
$selected_option = $_POST['num'];
foreach($options as $v){
if($v == $selected_option){
$selected = 'selected = "selected"';
}else{
$selected = '';
}
echo "<option value='$v' $selected>$v</option>";
}
?>
</select> entries
</form>
<table style="width:100%">
<thread>
<?php foreach ($fields as $field_name => $field_display): ?>
<th <?php if($sort_by == $field_name) echo "class=\"sort_$sort_order\"" ?>>
<?php echo anchor("rps/index/$field_name/".
(($sort_order == 'asc' && $sort_by == $field_name) ? 'desc' : 'asc'), $field_display); ?>
</th>
<?php endforeach; ?>
</thread>
<tbody>
<?php foreach ($record as $key): ?>
<tr>
<?php foreach ($fields as $field_name => $field_display): ?>
<td><?php echo $key->$field_name; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php if (strlen($pagination)): ?>
Pages: <?php echo $pagination; ?>
<?php endif; ?>
controller:
public function index($sort_by='player_item', $sort_order='asc',$offset=0)
{
if (isset($_POST['num']) && !empty($_POST['num']))
$limit = $this->input->post('num');
else
$limit= 25;
$data7['fields'] = array(
'id' => 'ID',
'time' => 'Time',
'player_item' => 'Player Choose',
'comp_item'=> 'Computer Choose',
'result'=> 'Result'
);
$this->load->model('rps_result');
$result = $this->rps_result->history($limit,$offset,$sort_by,$sort_order);
$data7['record'] = $result['rows'];
$data7['num_record'] = $result['number_rows'];
//pagination
$this->load->library('pagination');
$this->load->helper('url');
$config['base_url'] = "http://localhost/xampp/CodeIgniter/index.php/rps/index/$sort_by/$sort_order";
$config['total_rows'] = $data7['num_record'];
$config['per_page'] = $limit;
$config['uri_segment'] = 5;
$this->pagination->initialize($config);
$data7['pagination'] = $this->pagination->create_links();
$data7['sort_by'] = $sort_by;
$data7['sort_order'] = $sort_order;
$this->load->view('rps_result', $data7);
}
model:
function history($limit,$offset,$sort_by,$sort_order)
{
$sort_order = ($sort_order == 'desc') ? 'desc' : 'asc';
$sort_columns = array('id','player_item','comp_item','result','time');
$sort_by = (in_array($sort_by, $sort_columns)) ? $sort_by : 'time';
//result query
$query = $this->db->select('id,player_item,comp_item,result,time')
->from('rps')
->limit($limit,$offset)
->order_by($sort_by,$sort_order);
$ret['rows'] = $query->get()->result();
//count query
$query1 = $this->db->select('count(*) as count', FALSE)
->from('rps');
$tmp = $query1->get()->result();
$ret['number_rows'] = $tmp[0]->count;
return $ret;
}
Any help will be deeply appreciated.
You should pass 'num' from page to page. When you select the value, it gets the form submitted and the page is reloaded. But it doesn't use $_POST['num'] on the next pages, the value doesn't pass trough. The easyest way to fix this, would be to store the value in a cookie. In your controller instead of $limit = $this->input->post('num'); do
if($this->input->post('num')){
setcookie('pagination_limit',$this->input->post('num'));
$limit = $this->input->post('num');
}elseif($this->input->cookie('pagination_limit')){
$limit = $this->input->cookie('pagination_limit', true);
}else{$limit = 25;}
In your view, you should also repalace $_POST['num'] with $this->input->cookie('pagination_limit', true);

Categories