Subtraction of variable PHP - php

i cant figure out how can i subtract 2 from a variable ($energia) each time i click on a html link. Problem is that it only subtracts once, so the output will always be 18.
<?php
$energia = 20;
if(isset($_GET["action"]) && $energia != 0)
{
$energia -=2;
}
}
?>
<a href="?action" >subtract</a> <?php echo $energia2; ?>

Does this give you the result you want?
<?php
//checks if num is set, if not, set it to 20 by default
/*
The following line is the same as
if(isset($_GET["num"]))
{
$energia = $_GET["num"];
}
else
{
$energia = 20;
}
*/
//value condition if true else
$energia = isset($_GET["num"]) ? $_GET["num"] : 20;
//if action was clicked and energia is not 0 (not to go in negatives)
//remove && $energia != 0 to allow negative numbers
if(isset($_GET["action"]) && $energia != 0)
{
//substract 2 from energia
$energia -=2;
}
?>
This line sets action to true AND also stores the value of energia in the substact link string. When clicked, it is retrieved with $_GET["num"]. After the link, the current value (same as in the link) is shown to the user.
<a href="?action=true&num=<?php echo $energia; ?>" >subtract</a> <?php echo $energia; ?>

here is a jquery solution: jsfiddle
html
<span class="energia"></span>
<br/>
subtract
jquery
var energia = 20;
$('.energia').text(energia);
$(document).on('click','.subtract', function(){
energia -= 2;
$('.energia').text(energia);
return false;
});

Related

Value showing empty in browser , but its available in Database

Once we click on Download button, we are trying to download complete order details in pdf.... here 100452121 is orderid, xpress is shipping name & 14104918100111 is tracking id....
we set conditions that if tracking_id is empty, than it should echo 0 but we are getting zero [0] even when tracking_id available for the order....
Shippinglabel.php Full code in pastebin
<td><?php echo $orderrecords[$k]["order_id"]; ?><br/>
<?php
if ($st == 1) {
if ($orderrecords[$k]["tracking_id"] == '') {
?>
<input type="button" name="shipment" id="xpress" value="xpress"
onclick="createshipment('<?php echo $orderrecords[$k]["order_id"];?>')" />
<?php
}
}
?>
<?php
if ($orderrecords[$k]["tracking_id"] != '' && $orderrecords[$k]["shipping_name"] == 'xpress')
{
?>
<a target="_blank"
href="http://sbdev1.kidsdial.com/ecom1/xpress/xpressdownload.php?orderId=<?php
echo $orderrecords[$k]["order_id"];?>"
id="pdfdownload" >
<input type="button" name="shipment" value="DOWNLOAD" /></a>
<?php
}
?>
</td>
createshipment
function createshipment(orderid)
{
var assignee='<?php echo $_SESSION['login_user']?>';
alert(orderid);
$.ajax({
url: "xpressshipment.php",
type: "POST",
data:'orderid='+orderid+'&assignee='+assignee,
success: function(data){
if(data==1)
{
$("#pdfdownload").show();
}
if(data==0){alert("First Enter Tracking Id.");}
window.location ="http://sbdev1.kidsdial.com/ecom1/xpress/xpressdownload.php?orderId="+orderid;
}
});
}
xpressshipment.php Full code in pastebin
<?php
$data =
array (
'AirWayBillNO' => $resultc[0]['awb'],
);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$sqli="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' where order_id='".$order_id."'";
$resulti=$db_handle->executeUpdate($sqli);
}
?>
xpressdownload.php Full code in pastebin
<?php
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$orderid='';
$sqlorder = "SELECT tracking_id,order_id from do_order where order_id='".$orderid."' limit 1";
$resultdoorder = $db_handle->runSelectQuerys($sqlorder);
if($resultdoorder['tracking_id']=='')
{
echo 0;
//var_dump("tracking_id");
}
var_dump("tracking_id"); gave string(11) "tracking_id" as result....
please let me know if you need more details....
please help me to find solution....
Thanks in Advance....
In file xpressdownload.php you defined variable $orderid incorrectly.
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$orderid='';
First, you are checking whether $_GET['orderId'] exists and if yes, you give the value of $_GET['orderId'] to $orderid. This is correct.
But after the if... else block you give the $orderid the '' value. So in every case the $orderid has the null value and you sql query is not returning the record. You have to remove the line $orderid=''; or move it before the if statement.

Using GET, POST and GLOBALS

I'm trying to sort table of data by it's columns(as hyperlinks), but also to navigate using < or > buttons.
<?php
...
if (isset($_POST["next"]) && isset($_POST["start"]))
{
//force start to be an integer and add 5 to it
$start = (int)$_POST["start"] + 5;
}
elseif (isset($_POST["prev"]) && isset($_POST["start"]))
{
//force start to be an integer and remove 5 from it
$start = (int)$_POST["start"] - 5;
}
else
{
$start = 0;
}
// if one of hyperlinks in table heading was clicked
if (isset($_GET["sort"]))
{
$orderByFields = ["TerritoryDescription", "RegionDescription"];
$GLOBALS['sort'] = $_GET["sort"];
...
SQL here.
}
else
{
...
}
//problem here
// if next button was pressed
if (isset($_POST['next']))
{
echo 'next';
if (isset($_GET['sort']))
{
echo 'sort';
//undefined
//i'm trying to retrive value here.
echo $GLOBALS['sort'];
}
}
// if prev button was pressed
elseif (isset($_POST['prev']))
{
echo 'prev';
}
...
?>
I'm trying to retrieve value $GLOBALS['sort'] when < or > button was pressed so I can sort the SQL results by $GLOBALS['sort']. But the variable is undefined when I try to access from outside.

storing incremented value in session variable and printing it

Had googled this but maybe I'm not a good googler. My ultimate goal is to have a view more button that will read the next 6 files from a directory but before I do that I need to figure out this problem:
at the top of my index.php i have this:
<?php
if(session_id() == '') {
session_start();
$_SESSION["count"] = 0;
}
?>
lower down I have this:
<?php
function album() {
$_SESSION["count"]=$_SESSION["count"]+10;
echo $_SESSION["count"];
}
?>
when the user clicks a button its supposed to print the session variable + 10 on each click.. so 10 20 30 40 ..ect. But it keeps printing 10, it's not updating.
Always start session at the top of the page like
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] += 10;
echo $_SESSION["count"];
}
?>
You need to first do session_start() and then ask for $_SESSION.
<?php
session_start();
if(empty($_SESSION['count'])){
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] = $_SESSION["count"] + 10;
echo 'Count: '.$_SESSION["count"];
}
album();
?>
This I just tested it and it works fine.

Setting the default pagination page (Something to do with the loop?)

I am currently using the plugin WP-CommentNavi for comments pagination but whenever a page is clicked it goes to the highest comments page (oldest comments). My comments are purposely displayed newest first and therefore I need the default pagination page to be 1 whenever a link is clicked.
I notice there is the same default for other pagination plugins too whereby the highest pagination page (ie if there are 5 pages) page 5 is displayed.
At the moment when I load page tellhi####.com/newcastle the page that will be loaded is tellhi####.com/newcastle/comment-page-2/ whereas I want tellhi####.com/newcastle/comment-page-1/ to be loaded
I can't be sure this is the relevant code to what I am trying to achieve but I feel the answer might lie in here (below). If not, please tell me and disregard this code.
### Function: Comment Navigation: Boxed Style Paging
function wp_commentnavi($before = '', $after = '') {
global $wp_query;
$comments_per_page = intval(get_query_var('comments_per_page'));
$paged = intval(get_query_var('cpage'));
$commentnavi_options = get_option('commentnavi_options');
$numcomments = intval($wp_query->comment_count);
$max_page = intval($wp_query->max_num_comment_pages);
if(empty($paged) || $paged == 0) {
$paged = 1;
}
$pages_to_show = intval($commentnavi_options['num_pages']);
$pages_to_show_minus_1 = $pages_to_show-1;
$half_page_start = floor($pages_to_show_minus_1/2);
$half_page_end = ceil($pages_to_show_minus_1/2);
$start_page = $paged - $half_page_start;
if($start_page <= 0) {
$start_page = 1;
}
$end_page = $paged + $half_page_end;
if(($end_page - $start_page) != $pages_to_show_minus_1) {
$end_page = $start_page + $pages_to_show_minus_1;
}
if($end_page > $max_page) {
$start_page = $max_page - $pages_to_show_minus_1;
$end_page = $max_page;
}
if($start_page <= 0) {
$start_page = 1;
}
if($max_page > 1 || intval($commentnavi_options['always_show']) == 1) {
$pages_text = str_replace("%CURRENT_PAGE%", number_format_i18n($paged), $commentnavi_options['pages_text']);
$pages_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pages_text);
echo $before.'<div class="wp-commentnavi">'."\n";
switch(intval($commentnavi_options['style'])) {
case 1:
if(!empty($pages_text)) {
echo '<span class="pages">'.$pages_text.'</span>';
}
if ($start_page >= 2 && $pages_to_show < $max_page) {
$first_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $commentnavi_options['first_text']);
echo ''.$first_page_text.'';
if(!empty($commentnavi_options['dotleft_text'])) {
echo '<span class="extend">'.$commentnavi_options['dotleft_text'].'</span>';
}
}
previous_comments_link($commentnavi_options['prev_text']);
for($i = $start_page; $i <= $end_page; $i++) {
if($i == $paged) {
$current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['current_text']);
echo '<span class="current">'.$current_page_text.'</span>';
} else {
$page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['page_text']);
echo ''.$page_text.'';
}
}
next_comments_link($commentnavi_options['next_text'], $max_page);
if ($end_page < $max_page) {
if(!empty($commentnavi_options['dotright_text'])) {
echo '<span class="extend">'.$commentnavi_options['dotright_text'].'</span>';
}
$last_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $commentnavi_options['last_text']);
echo ''.$last_page_text.'';
}
break;
case 2;
echo '<form action="'.admin_url('admin.php?page='.plugin_basename(__FILE__)).'" method="get">'."\n";
echo '<select size="1" onchange="document.location.href = this.options[this.selectedIndex].value;">'."\n";
for($i = 1; $i <= $max_page; $i++) {
$page_num = $i;
if($page_num == 1) {
$page_num = 0;
}
if($i == $paged) {
$current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['current_text']);
echo '<option value="'.clean_url(get_comments_pagenum_link($page_num)).'" selected="selected" class="current">'.$current_page_text."</option>\n";
} else {
$page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['page_text']);
echo '<option value="'.clean_url(get_comments_pagenum_link($page_num)).'">'.$page_text."</option>\n";
}
}
echo "</select>\n";
echo "</form>\n";
break;
}
echo '</div>'.$after."\n";
}
}
In short I need, anytime a page is clicked, for the comments pagination to be on page 1, not the highest page available. Just so you know I have tried the discussion settings on the wordpress dashboard. Nothing on google either!
Failing a full answer, does anyone know the actual php code that determines what pagination page is loaded by default?
I received this response via an e-mail but due to my PHP knowledge am unable to implement it, any ideas? ...
Just reverse the loop. That'll fix it. Here's the relevant part:
http://pastie.org/8166399 You need to go back, i.e. use $i--
Would this change the default start page or just reverse the comments? Hope I have been clear in my question! Will appreciate any response at all.
Thanks in advance, Paul
The option was in Wordpress all along. See picture: http://oi40.tinypic.com/35aj3pt.jpg
If anyone has the answer to the specific code you manipulate, still answer the question here because someone doing this without Wordpress could very well encounter this problem also.

Problems with current tab and page numbers in php

there i have created a program with a tab button and page number. all functions are almost working properly until i noticed one tiny problem. as we all know, tabs always highlights the current tab you are in. let us say if your tabs are A-Z letters and a # that means home or mainpage, and your # is the current page, and the main pages consist of the list of employees registered in your database. since i have page number (Next and Previous), i have limited the amount or number of employee names/information by 5 stating that only 5 records should appear on the screen.
note: my code is working, but 1 problem slipped. everytime i clicked on the next button to see the other list of employees,the # tab is not highlighted wherein its suppose to still be highlighted since you are in the same page. Does anyone knows what cause this and how to fix it? im sorry if it is not that clear since it is so hard to explain.
example:(IMAGINE THIS AS THE WINDOW) let us say the limit is = 2
**#** A B C D E F G H I J K L M N O P Q R S T U V W X Y Z //this is the tabs button, notice the # is highlighted
employee_id : employee_name : employee_age
1 chel 26
2 brandon 35
**PREV** **NEXT** //this is the page number
when i try to click next to view the next employee in the main page, the page looks like this:
# A B C D E F G H I J K L M N O P Q R S T U V W X Y Z //notice the # is NOT highlighted after you click next
employee_id : employee_name : employee_age
3 charlie 28
4 sasha 24
**PREV** **NEXT**
i hope i cleared up my problem in this simple illustration. i hope someone could help me. thanks
//this is my tabs codes
<?php
function toc_menu($current){
$return ='<ol id="toc">
'."\n";
$return .= ($current=='') ? '<li class="current"><span>#</span></li>'."\n" : '<li><span>#</span></li>'."\n";
foreach(range('a','z') as $link){
$return .= ($current==$link) ? '<li class="current"><span>'.strtoupper($link).'</span></li>'."\n" : '<li><span>'.strtoupper($link).'</span></li>'."\n";
}
$return .="</ol>\n";
return $return;
}
if(isset($_GET['namelist']))
{
$current=$_GET['namelist'];
}
else
{$current='';
}
//echo where you want the menu
if(isset($_GET['namelist'])) {
echo toc_menu(strtolower($_GET['namelist']));
$tocmenu = toc_menu(strtolower($_GET['namelist']));
} else {
echo toc_menu(strtolower(''));
}
//or hold it in a variable to display later on
?>
//and this is my page_number codes:
<?php if ($offset>=1)
{ // bypass PREV link if offset is 0
$prevoffset=$offset-$limit;
print "<a href=\"".htmlentities($_SERVER['PHP_SELF'])."?offset=$prevoffset&searchfile=$search&namelist=$listname\"/>Prev</a> ";
}
echo '</td>
<td colspan ="5" height ="20" align="right"';
// check to see if last page
if (!($offset+$limit > $total))
{
// not last page so give NEXT link
if ($offset == 1)
{
$newoffset=$offset+($limit-1);
}
else
{
$newoffset=$offset+$limit;
}
print "Next ";
}
?>
TAKE NOTE:
My variable namelist is used for the A-Z variable
the searchfile is for my search button
MisaChan
After struggling with this long piece of code the only thing that i see that can be causing an issue is $listname
if listname is not a letter your code will not work.
here is what i suggested, since your code is not sorted alphabetically you should consider using numbers instead. A-Z will be 1 to 10 or 1 to total pages it makes much more sense,
here is a class that i use to handle pagination easily
class Pagination {
public $current_page;
public $per_page;
public $page_count;
public function __construct($page=1,$per_page= 15, $total_count=0) {
$this->current_page = $page;
$this->per_page = $per_page;
$this->total_count = $total_count;
}
public function offset() {
return ($this->current_page -1)* $this->per_page;
}
public function total_pages () {
return ceil($this->total_count/ $this->per_page);
}
public function previous_page () {
return $this->current_page -1;
}
public function next_page () {
return $this->current_page +1;
}
public function has_previous_page () {
return $this->previous_page() >= 1? true : false;
}
public function has_next_page () {
return $this->next_page() <= $this->total_pages()? true : false;
}
// edit this section to suit your needs
public function format_output ($link,$query) {
if ($this->total_pages() > 1) {
$output = "<div id=\"pagination\"><p>";
$output .= ($this->has_previous_page())? ("<a href=\"/$link/".$this->previous_page()."/{$query}\" >Previous</a>"): "";
$c = $this->current_page;
$t = $this->total_pages();
for ( $i = 1; $i <= $t; $i++ )
{
if ($this->current_page == $i) {
$output .= " <a class=\"active\" href=\"#\" >{$i}</a> ";
}else {
$output .= " <a href=\"/$link/{$i}/{$query}\" >{$i}</a> ";
//$output .= " <a href=\"$link?q={$query}&page={$i}\" >{$i}</a> ";
}
}
$output .= (($t ==$this->total_pages())?"":' ... ');
$output .= ($this->has_next_page())? ("<a href=\"/$link/".$this->next_page()."/{$query}\" >Next</a>"): "";
$output .= "</p></div>";
}else {
$output = "<div id=\"pagination\"><p>Displaying all results.</p></div>";
}
return $output;
}
}
?>
and here is how i use it.
// your listname in numbers
$currentPage = isset($_GET['currentPage'])? $_GET['currentPage']: 1; // page number
$limit =2; // you decided to limit 2 per page
$total = 10; // the total result available in all pages
$pagination = new Pagination($currentPage, $limit,$total);
// if you need the the value of how many to offset for the current page
$offset = $pagination->offset(); // example page 6 will return 12
// and to display the pagination simply echo this
echo $pagination->format_output(htmlentities($_SERVER['PHP_SELF']),'other values u want to pass');
This will automatically create the previous and next button for you
I hope this will help you solve your problem

Categories