Codeigniter Days Left mysql Query - php

I have a simple script that displays products. In my database I store both date_posted and end_date as fields in he products table. On my homepage I display the 20 most recent posted products.
I want to display products that have 1 or more days left. So far I've manage to do this but using the front end script and css and this isn't best practice because it won't display 20 products if some among them have ended.
Below is the script that i have:
my View =>
<?php $i=0;?>
<?php foreach($product as $p): ?>
<?php
$startDate = date('m/d/Y');
$endDate = $p['endDate'];
$seconds_left = (strtotime($endDate) - strtotime($startDate));
$days_left = floor($seconds_left / 3600 / 24);
?>
<?php $i+= 1; ?>
<td <?php //if($days_left<=0){echo "class='ended'";} ?>>
<a href="<?php echo base_url()."user/product/".$p['productID']; ?>" class="product_name"><?php echo $p['productName']; ?>
</a>
<ul class="nav">
<li><i class="icon-home"> </i> Location : <?php echo substr($p['location'],0,25); ?></li>
<li><i class="icon-tags"> </i> Budget : Tshs <?php echo number_format($p['Price']); ?></li>
<li><i class="icon-tasks"> </i> <?php if($p['CategoryID']==4){echo"Number of rooms: ";}else echo "Quantity :"?> <?php echo $p['quantity']; ?></li>
<li><i class="icon-eye-open"> </i> Bids : <?php echo $p['Bids']; ?></li>
<li><i class="icon-time"> </i> Days Left: <?php echo $days_left; ?></li>
</ul>
</td>
my Model=>
function get_product($productID){
$this->db->select()->from('products')->where('productID',$productID);
$query = $this->db->get();
return $query->first_row('array');
}

You'll need to get a date in your where clause.
Something like this should do the trick:
function get_product($productID){
$this->db->select()
->from('products')
->where('productID',$productID)
->where('end_date >=', date('Y-m-d H:i:s', strtotime('- 1 day')))
->limit(20);
$query = $this->db->get();
return $query->first_row('array');
}

Related

The problem of cannot pass ?= value in php pagination

I have do a pagination with php&html,the problem is my $page is always equal 1 even I click another page and the url is already become ?page=2.The value $p cannot pass as $page.How can I solve this?
<ul class="nospace clear" style="width:1310px;">
<?php
if(isset($_GET['page'])&& $_GET['page']!=""){$page = $_GET["page"];}else{$page=1;}
$current=$page;
$end=12;
if($page=1){$start=0;$previous=$page;$next=$page+1;}
else if($page<=12){$start=$page*12-12;$previous=$page-1;$next=$page+1;}
else{$start=0;$previous=$page-1;$next=12;}
$sql = "Select * from item where Gender='women' AND Category='cloth' LIMIT $start,$end";
$result = mysqli_query($connect,$sql);
while($row=mysqli_fetch_assoc($result)){?>
<img src="../images/demo/<?php echo $row["Pic"]; ?>" style="width:300px;height:280px"><br><p></p><h3><strong><?php echo $row["Name"]; ?></strong></h3><p><?php echo $row["Description"]; ?></p></li>
<?php } ?></ul><figcaption>Page <?php echo"$page ";?> end...</figcaption>
</figure>
</div>
<nav class="pagination">
<ul>
<li>« Previous</li>
<?php
for ($p=1;$p<13;$p++){
if ($page == $p) {?>
<li class="current btn1"><strong><?php echo $p ?></strong></li><?php }
else{?><li><a href="?page=<?php echo $p ?>" class='btn1'><?php echo $p ?></a></li><?php }}?>
<li> Next » </li>
</ul>

How to call user specific data from an external database into WordPress

Here is the challenge and I am sure this is not the first time someone has came into this issue however have not found a viable solution pertaining to this specific process within the pages of stackoverflow or any other development forum for that matter.
Here is the task I am trying to complete.
I have built a WordPress website which will be a members area where only registered users may log into the site to view its content. This functionality will be done through WordPress however I have a page within WordPress titled "Member Status" that I have created a custom page template for in order to pull information that will be user specific to a form on that page. The user specific information is being pulled from a secondary external database to the WP database.
Here is the code for the custom page template for a better visual of what I am trying to do. Basically all form fields would be populated from the specific row of that specified user. however the query seems to fail everytime and am wondering if I should be adding this table to my WP db, if that would rectify the issue or is there a fault in my code I am just not seeing.
<?php
$servername = "localhost";
$username = "DBusername";
$password = "DBpassword";
$database = "DBname";
// Create connection
$conn = new mysqli($servername, $username, $password);
$db_selected = mysqli_select_db($conn, $database);
$userid = $current_user->user_login;
$sql = "SELECT * FROM 'member-status' WHERE 'Card' = '$userid'";
$result = mysqli_query($conn, $sql);
if ($result) {
list($userid) = mysqli_fetch_array(mysqli_query($result));
} else {
echo "query failed";
}
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<?php
while ($row = mysqli_fetch_assoc("$sql"))
?>
<div class="Disclaimer_webpage">
<?php echo $row["Disclaimer_WebPage"]; ?>
</div>
<div class="OuterBlock">
<div class="oneblock">
<ul>
<li>LAST</li>
<li><?php echo $row["Last"]; ?></li>
</ul>
<ul>
<li>FIRST</li>
<li><?php echo $row["First"]; ?></li>
</ul>
<ul>
<li>CARD</li>
<li><?php echo $row["Card"]; ?></li>
</ul>
<ul>
<li>CLASS</li>
<li><?php echo $row["Class"]; ?></li>
</ul>
</div>
<div class="secblock">
<ul>
<li>DATE SIGNED BOOK</li>
<li>
<?php if ($row['StartDate']!=""){ echo date('m/d/y', strtotime($row["StartDate"])); } ?>
</li>
</ul>
<ul>
<li>OUT OF WORK DATE</li>
<li>
<?php if($row['CURROOWD']!=""){ echo date('m/d/y', strtotime($row["CURROOWD"])); } ?>
</li>
</ul>
<ul>
<li>DISPATCH UNIT</li>
<li><?php echo $row["OriginalUnit"]; ?></li>
</ul>
<ul>
<li>DAYS DISPATCHED (OF 140)</li>
<li><?php echo $row["DAYS140"]; ?></li>
</ul>
</div>
<div class="over_all_list_position">
<ul>
<li><b>OVER ALL LIST POSITION</b><span class="information_Icon"><img src="http://redsealcreative.com/clients/353-members/wp-content/plugins/IBEWJOBLISTS/Info.png" > <p class="imgDescription">Your position on the Out of Work List.</p></span><span class="see_below"> (*see below)</span></li>
<li><?php echo $row["ListPosition"]; ?></li>
</ul>
<ul>
<li><b>UNIT LIST POSITION</b><span class="information_Icon1"><img src="http://redsealcreative.com/clients/353-members/wp-content/plugins/IBEWJOBLISTS/Info.png" > <p class="imgDescription1">Your list position relative only to members in your Dispatch Unit.</p><span></li>
<li><?php echo $row["LISTPOS_UNIT"]; ?></li>
</ul>
<ul>
<li><b>OPG LIST POSITION</b><span class="information_Icon2"><img src="http://redsealcreative.com/clients/353-members/wp-content/plugins/IBEWJOBLISTS/Info.png" > <p class="imgDescription2">Your list position relative only to those with current OPG Security Clearance.</p><span></li>
<li><?php echo $row["LISTPOS_OPG"]; ?></li>
</ul>
</div>
<div class="fothblock">
<ul>
<li>PASSES</li>
<li>NORTH UNIT</li>
<li>SOUTH UNIT</li>
<li>EAST UNIT</li>
</ul>
<ul>
<li>ACCUMULATED</li>
<li><?php echo $row["PassNorthAcc"]; ?></li>
<li><?php echo $row["PassSouthAcc"]; ?></li>
<li><?php echo $row["PassEastAcc"]; ?></li>
</ul>
<ul>
<li>MAXIMUM</li>
<li><?php echo $row["PassNorthMax"]; ?></li>
<li><?php echo $row["PassSouthMax"]; ?></li>
<li><?php echo $row["PassEastMax"]; ?></li>
</ul>
</div>
<div class="sixblock">
<ul>
<li>LAST OUT WORK DATES DISPATCHED</li>
<li>NORTH</li>
<li>SOUTH</li>
<li>EAST</li>
<li>OUT OF TOWN</li>
</ul>
<ul>
<li class="padding-top"></li>
<li class="padding-top"><?php if($row['LOOWDN']!=""){echo date('m/d/y', strtotime($row["LOOWDN"])); }?></li>
<li><?php if($row['LOOWDS']!=""){ echo date('m/d/y', strtotime($row["LOOWDS"])); } ?></li>
<li class="padding-top"><?php if($row['LOOWDE']!=""){echo date('m/d/y', strtotime($row["LOOWDE"]));} ?></li>
<li><?php if($row['OOTOOWD']!=""){echo date('m/d/y', strtotime($row["OOTOOWD"]));} ?></li>
</ul>
</div>
<div class="seven">
<ul>
<li>LAST UPDATED</li>
</ul>
<ul>
<li class="padding-top"><?php echo $row["TIME_STAMP"]; ?></li>
</ul>
</div>
</div>
<div class="Disclaimer_POL">
<?php echo $row["Disclaimer_POL"]; ?>
</div>
All insight will be gratefully appreciated. Thanks in advance for the communities assistance to a new member. :)
UPDATE #2 ISSUE RESOLVED
I am happy to announce that I figured out the issue. For anyone else that is wanting to accomplish this task here is the working code that I used.
<?php global $current_user;
wp_get_current_user(); ?>
<?php
// $mydb = new wpdb('username','password','database','localhost');
//$mydb->show_errors();
$userid = $current_user->user_login;
$result = $wpdb->get_results( "SELECT * FROM member_status WHERE CARD = $userid");
// $query = "SELECT * FROM member_status WHERE CARD = $userid";
// $result = $mydb->get_results($query);
?>
<?php foreach ( $result as $query ) {?>
Then to call the individual fields/column data add this code where you want it located
<?php echo $query->ColumnName; ?> //Change ColumnName to the column you want to call from.
I hope this comes in handy for you all :)
I am happy to announce that I figured out the issue. For anyone else that is wanting to accomplish this task here is the working code that I used.
<?php global $current_user;
wp_get_current_user(); ?>
<?php
// $mydb = new wpdb('username','password','database','localhost');
//$mydb->show_errors();
$userid = $current_user->user_login;
$result = $wpdb->get_results( "SELECT * FROM custom_table WHERE Column = $userid");
// $query = "SELECT * FROM custom_table WHERE Column = $userid";
// $result = $mydb->get_results($query);
?>
<?php foreach ( $result as $query ) {?>
Then to call the individual fields/column data add this code where you want it located
<?php echo $query->ColumnName; ?> //Change ColumnName to the column you want to call from.
I hope this comes in handy for you all :)

How can set different arrays that deals with different range of values?

I want to achieve the following html dynamically:
Time period AD:
<ul>
<li>1200</li>
<li>1300
<ul>
<li>1301</li>
</ul>
<li>
</ul>
Time period BC:
<ul>
<li>-200</li>
<li>-450
<ul>
<li>-451</li>
</ul>
</li>
</ul>
In the following I have set an array so that I can, by using some custom fields, push my dates into the array, then tell the whole code to calculate in 100 of years, in order to be able to place years like 1301 as a nested ul under 1300.
<ul>
<?php
$yearsArray = [];
$centuryHash = [];
query_posts(array(
'post_type' => 'post',
'posts_per_page' => -1
));
while ( have_posts() ) : the_post();
array_push($yearsArray, get_field("year"));
if (($wp_query->current_post +1) == ($wp_query->post_count)) {
$yearsArray = array_unique($yearsArray);
sort($yearsArray);
}
endwhile;
foreach ($yearsArray as $year) {
$currentCentury = floor($year/100)*100;
if(!$centuryHash[$currentCentury]){
$centuryHash[$currentCentury] = [];
}
if($currentCentury != $year){
$centuryHash[$currentCentury][] = $year;
}
}
foreach ($centuryHash as $century => $centuryYears) { ?>
<li class="dropdown">
<?php if($centuryYears){ ?>
<a class="btn btn-default" href="#" class="dropdown-toggle" data-date="<?php echo $century; ?>" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<?php echo $century; ?>
<span class='caret'></span>
</a>
<ul class='dropdown-menu'>
<?php foreach ($centuryYears as $year) { ?>
<li>
<a class="btn btn-default" data-date="<?php echo $year; ?>" href="#">
<?php echo $year; ?>
</a>
</li>
<?php }
echo "</ul>";
} else { ?>
<a class="btn btn-default" data-date="<?php echo $century; ?>" href="#">
<?php echo $century; ?>
</a>
<?php } ?>
</li>
<?php }
?>
</ul>
The problem that I can't figure out is how I can say like (verbal code):
If value is within the range of -450 till 2 then go into this array otherwise go in that array instead
From my end I could set in the cms (people will be able to insert content with dates) some flags so that I can do simple conditionals like (verbal code):
"Is this date from a or b? then do this or that"
But that creates an issue because I could flag a period of time and place the wrong date in the wrong period.
Therefore the last solution that I thought is to set a range of periods of times and delimiter some arrays by create different ones where I could dynamically push the values depending on their values.
This could be a start maybe (example from docs)? But how can I set an if to control what goes there or not?
foreach (range(0, 12) as $number) {
echo $number;
}
Here is a simple answer to your question.
If value is within the range of -450 till 2 then go into this array otherwise go in that array instead
if ($value >= -450 && $value <= 2) {
// do this
} else {
// do that
}
Hope, this answers to your question (which is, unfortunately, overloaded with dozens of code that doesn't apply to the question).

Joomla k2 archive module sort by year and by month

I'm using joomla with K2 and I want to order news in The archive module first by year. When you click on The year it Needs to show all articles from that year. Bit The module also Needs to expand The months to filter deeper
How can I modify the module to act like This?
Greets
So this is what I mean
2012
- Januari
- Februari
- March
- etc etc
2013
- Januari
- Februari
- March
- etc etc.
Both year and month needs to be filterable
How can I modify the module to act like This?
Greets
So this is what I mean
List item
2012
Januari
Februari
March
etc etc
2013
Januari
Februari
March
etc etc.
Both year and month needs to be filterable
How can I modify the module to act like This?
Greets
<div id="k2ModuleBox<?php echo $module->id; ?>" class="k2ArchivesBlock<?php if($params->get('moduleclass_sfx')) echo ' '.$params->get('moduleclass_sfx'); ?>">
<ul>
<?php foreach ($months as $month): ?>
<li>
<?php if ($params->get('archiveCategory', 0) > 0): ?>
<a href="<?php echo JRoute::_('index.php?option=com_k2&view=itemlist&task=date&month='.$month->m.'&year='.$month->y.'&catid='.$params->get('archiveCategory')); ?>">
<?php echo $month->name.' '.$month->y; ?>
<?php if ($params->get('archiveItemsCounter')) echo '('.$month->numOfItems.')'; ?>
</a>
<?php else: ?>
<a href="<?php echo JRoute::_('index.php?option=com_k2&view=itemlist&task=date&month='.$month->m.'&year='.$month->y); ?>">
<?php echo $month->name.' '.$month->y; ?>
<?php if ($params->get('archiveItemsCounter')) echo '('.$month->numOfItems.')'; ?>
</a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
The query is from another file
public static function getArchive(&$params)
{
$mainframe = JFactory::getApplication();
$user = JFactory::getUser();
$aid = (int)$user->get('aid');
$db = JFactory::getDBO();
$jnow = JFactory::getDate();
$now = K2_JVERSION == '15' ? $jnow->toMySQL() : $jnow->toSql();
$nullDate = $db->getNullDate();
$query = "SELECT DISTINCT MONTH(created) as m, YEAR(created) as y FROM #__k2_items WHERE published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) AND trash=0";
if (K2_JVERSION != '15')
{
$query .= " AND access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
if ($mainframe->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") ";
}
}
else
{
$query .= " AND access<={$aid} ";
}
$catid = $params->get('archiveCategory', 0);
if ($catid > 0)
$query .= " AND catid=".(int)$catid;
$query .= " ORDER BY created DESC";
$db->setQuery($query);
$rows = $db->loadObjectList();
$months = array(JText::_('K2_JANUARY'), JText::_('K2_FEBRUARY'), JText::_('K2_MARCH'), JText::_('K2_APRIL'), JText::_('K2_MAY'), JText::_('K2_JUNE'), JText::_('K2_JULY'), JText::_('K2_AUGUST'), JText::_('K2_SEPTEMBER'), JText::_('K2_OCTOBER'), JText::_('K2_NOVEMBER'), JText::_('K2_DECEMBER'), );
if (count($rows))
{
foreach ($rows as $row)
{
if ($params->get('archiveItemsCounter'))
{
$row->numOfItems = modK2ToolsHelper::countArchiveItems($row->m, $row->y, $catid);
}
else
{
$row->numOfItems = '';
}
$row->name = $months[($row->m) - 1];
$archives[] = $row;
}
return $archives;
}
}
This solved my issue:
<div id="k2ModuleBox<?php echo $module->id; ?>" class="k2ArchivesBlock<?php if($params->get('moduleclass_sfx')) echo ' '.$params->get('moduleclass_sfx'); ?>">
<?php
foreach ($months as $month) {
$years[$month->y][] = $month;
}
?>
<?php foreach ($years as $year => $months) : ?>
<h4><?php echo $year; ?></h4>
<ul>
<?php foreach ($months as $month): ?>
<li>
<?php if ($params->get('archiveCategory', 0) > 0): ?>
<a href="<?php echo JRoute::_('index.php?option=com_k2&view=itemlist&task=date&month='.$month->m.'&year='.$month->y.'&catid='.$params->get('archiveCategory')); ?>">
<?php echo $month->name.' '.$month->y; ?>
<?php if ($params->get('archiveItemsCounter')) echo '('.$month->numOfItems.')'; ?>
</a>
<?php else: ?>
<a href="<?php echo JRoute::_('index.php?option=com_k2&view=itemlist&task=date&month='.$month->m.'&year='.$month->y); ?>">
<?php echo $month->name.' '.$month->y; ?>
<?php if ($params->get('archiveItemsCounter')) echo '('.$month->numOfItems.')'; ?>
</a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
</div>

How can I do this query in CodeIgniter

this is the controller method
public function ajaxLoad()
{
$data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
$data['content'] = $this->load->view('item', $data, true);
$data = json_encode($data);
echo $data;
}
and this is the js that invokes ajax
var tempScrollTop, currentScrollTop = 0;
$(document).scroll(function(){
currentScrollTop = $(document).scrollTop();
if (tempScrollTop < currentScrollTop )
{
var result = currentScrollTop % 100;
if(result == 0)
{
$.ajax({
url: "ajax/load",
type: "POST",
success: function(res){
$("#content").html(res);
}
});
}
}
else if (tempScrollTop > currentScrollTop )
{
var result = currentScrollTop % 100;
if(result == 0)
{
$("#content").text("Вверх запрос " + result);
}
}
tempScrollTop = currentScrollTop;
})
the problem i that i can't get the part of a page with the query that goes in the content and then json_encode to transfer to javascript, if i remove the
$data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
and change this to
$data['content'] = $this->load->view('item', null, true);
thus without the $data object its ok.
then its comes empty, but i need the database rows to display in the content
how can i solve this problem??
and the echo $data; - its the only way to transfer the data to js??, i tried return $data;, but that doesn't work :(
and also the main problem is that the PHP generates the page with the foreach function that generates records by loop, but if i put one of those records with ajax will the variables inside that partial become values of the database query??, or i need to set the values with js??
i am confused about that, sorry if i am wrong, can you help me???
so this is how looks the page generated by php by when the pages loads:
<? $i = 1 ?>
<? foreach($query->result() as $q): ?>
<?
$milliseconds = $q->end;
//echo $dd;
//echo time();
/*
$year = date('y', $t);
$month = date('m', $t);
$day = date('d', $t);
$hour = date('h', $t);
$minute = date('i', $t);
$second = date('s', $t);
*/
$d = new Datecalc;
$begin = date("Y-m-d H:i:s");
$end = date($q->end);
#$date = $d->dateDiff($begin , $end);
//$begin = strtotime($begin);
//$end = strtotime($q->end);
$d->dateDiff($begin, $end);
//echo $d->day;
$desc = substr($q->desc, 0, 225);
if(strlen($desc) > 180)
{
$desc = $desc."...";
}
?>
<input type="hidden" value="<?= $milliseconds ?>" id="milliseconds_<?= $q->id ?>" />
<div class="item" id="item_<?= $q->id ?>">
<? if(!empty($_SESSION['role']) && $_SESSION['role'] == 'admin'): ?>
<div class="admin_delete">
<?= img('css/img/admin_delete.png'); ?>
</div>
<? endif; ?>
<div class="desc">
<span class="discount">Скидка <?= $q->discount ?>%</span>
<span class="desc"><?= $desc ?></span>
</div>
<div class="item_pic">
<? $attr = array('src' => $q->image,
'id' => 'item_pic',
'class' => 'item_pic') ?>
<?= img($attr) ?>
</div>
<div class="menu_3">
<ul class="menu_3">
<li class="timer">
<? $attr = array('src' => 'css/img/time.png',
'class' => 'time') ?>
<?= img($attr) ?>
<span id="days_<?= $q->id?>"><?= $d->day ?></span>д.
<span id="hours_<?= $q->id?>"><?= $d->hour ?></span> :
<span id="minutes_<?= $q->id?>"><?= $d->min ?></span> :
<span id="seconds_<?= $q->id?>"><?= $d->sec ?></span>
</li>
<li class="price">
<?= $q->price ?>с.
</li>
<li class="buy">
<div class="small">
99
</div>
<a href="<?= base_url() ?>buy/<?= $q->id ?>">
<?= img('css/img/kupit.png') ?>
</li>
<li class="item_arrow">
<?= img('css/img/item_arrow.png') ?>
<? if($i % 2 == 0): ?>
<ul class="submenu2">
<? else: ?>
<ul class="submenu2">
<? endif; ?>
<li>
<a href="<?= base_url() ?>show/<?= $q->id ?>">
Подробнее
</a>
</li>
<li>
Как это работает
</li>
<li style="border-bottom: none;">
Рассказать друзьям
</li>
<li style="border-bottom: none;">
<?= img('css/img/namba.png') ?>
<?= img('css/img/mail_ru.png') ?>
<?= img('css/img/odnoklassniki.png') ?>
<?= img('css/img/vkontakte.png') ?>
<?= img('css/img/facebook.png') ?>
</li>
</ul>
</li>
</ul>
</div>
</div>
<? $i++; ?>
<? endforeach; ?>
<div class="clear"></div>
i dont know how to put the records by ajax separately gradualy when the user scrolls down
Try rewriting these two lines
$data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
$data['content'] = $this->load->view('item', $data, true);
as
$db_data['query'] = $this->db->query("SELECT * FROM items ORDER BY id DESC");
$data['content'] = $this->load->view('item', $db_data, true);
As it is, you are sending, as part of the JSON output, the query response from the DB (in the $data array). Then replace the last two lines with
echo json_encode($data);

Categories