Using GET, POST and GLOBALS - php

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.

Related

How to use next/previous button without redirecting to the php files?

I need help with my code as of now i have this
https://i.stack.imgur.com/b5yJL.png
this is my table, it wont display any row until someone will press the search button,. if they did it will display this
https://i.stack.imgur.com/9TpGG.png
a list of row from database with pages, my problem is when i click the page it will display like this
https://i.stack.imgur.com/6S4Nl.png it wont stay in the current page but redirect to the php files and i dont have any idea on what to do, the button is working btw, and it show the next right table in each page
here is my code for the page button
if($page>1)
{
echo "<a href='/api2/allrecords.php?page=".($page-1)."' class='btn btn-danger'>Previous</a>";
}
for($i=1;$i<$total_page;$i++)
{
echo "<a href='/api2/allrecords.php?page=".$i."' class='btn btn-primary'>$i</a>";
}
if($i>$page)
{
echo "<a href='/api2/allrecords.php?page=".($page+1)."' class='btn btn-danger'>Next</a>";
}
and here is for the sql
if(isset($_GET['page']))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$num_per_page = 20;
$start_from = ($page-1)*02;
$connect = mysqli_connect("127.0.0.1", "crudDBck69t", "NTCHilrXdf", "crudDBck69t");
$output = '';
$query = "
SELECT * FROM rvtable limit $start_from,$num_per_page
";
$pr_query = "select * from rvtable";
$pr_result = mysqli_query($connect,$pr_query);
$total_record = mysqli_num_rows($pr_result );
$total_page = ceil($total_record/$num_per_page);
$result = mysqli_query($connect, $query);
there are all in the same php files call
allrecord.php, but im displaying it on wordpress page.,
this is how i call it in my costume page template in wordpress
if(from_date == '' && to_date == '' && search == '') {
$.ajax({
url:"/api2/allrecords.php",
method:"POST",
data:{from_date:from_date, to_date:to_date, search:search},
success:function(data)
{
$('#rvoucher').html(data);
}
});
}
and its working well except the page button, should i change the link on it? but the $_GET is on allrecord.php file
any idea?
thanks
The problem you are having is that the POST data is not sent together with your GET request when the user clicks the link that is the next page button.
One solution could be to instead of using links where the href reloads the page use links that have a click event listener that would run your POST request again but only this time with the page selected.
Another thing, you shouldn't really be taking use input and putting it directly into your SQL queries as that exposes you solution to SQL injection
example of how to output buttons that should reload the table with the search data:
<script type="text/javascript">
function gotoPage(page) {
$.ajax({
url:"/api2/allrecords.php?page=" + page,
method:"POST",
data: {
from_date: atob("<?php echo base64_encode($_POST['from_date'] ?? ''); ?>"),
to_date: atob("<?php echo base64_encode($_POST['to_date'] ?? ''); ?>"),
search: atob("<?php echo base64_encode($_POST['search'] ?? ''); ?>"),
},
success: function(data) {
$('#rvoucher').html(data);
}
});
}
</script>
<?php
if ($page > 1) {
echo 'Previous';
}
for($i=1; $i < $total_page; $i++) {
echo '' . $i . '';
}
if($page < $total_page) {
echo 'Next';
}
?>

Subtraction of variable 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;
});

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.

Making a virtual shelf and populating it via a database

I'm trying to make a virtual shelf type of thing which is populated via a MySQL database. The column shelfPos holds the position of the item on the shelf. Each row/'shelf' starts with <div class="shelfRow"> and obviously ends with </div> so it's styled and positioned correctly. Items on the shelves can be moved around using the jQuery UI droppable interaction.
The overall layout is this: http://jsfiddle.net/aRA5D/
Each shelf can hold 5 items (left to right).
I'm having trouble populating the shelves. At the moment I've got this: (This is in the place of the HTML)
<?php
$sql="SELECT * FROM shelf WHERE userID='$userID'";
$result=mysql_query($sql);
if (mysql_num_rows($result) == 0) {
// Show a message of some sort? (No items)
}
else {
$tries = 1;
$times = 10; // How many shelves. (10 = 2 shelves)
while(($row = mysql_fetch_array($result)) && ($tries <= $times)) {
while ($tries <= $times) {
if ($tries == $row['shelfPos']) {
echo '<div class="drop" id="drop'.$tries.'"><div class="boxArt" id="'.$row['gameID'].'">'.$row['gameID'].'</div></div>';
}
else {
echo '<div class="drop" id="drop'.$tries.'"></div>';
}
$tries = $tries + 1;
}
$times = $times + 5;
}
}
?>
There's several things wrong with it. It doesn't include the <div class="shelfRow"> html (didn't know how/where to put it, as it needs to be echoed after every 5 'blank' and real items - for loop maybe?) and it requires me to input the number of shelves (2 in this case). Would it be possible to determine how many shelves are required based on the item's position? It's awkward to do because it also needs to echo 'blank' .drop divs before and after them so that the items can be moved around.
Hope this all makes sense. Thanks for the help!
First u need to get data in order of ShelfPos
"SELECT * FROM shelf WHERE userID='$userID' order by shelfPos asc"
And try this code:
...
$i = 0;
while($row = mysql_fetch_array($result)) {
//Each 5
if($i % 5 == 0) echo '<div class="shelfRow">';
if ($i == $row['shelfPos']) {
echo '<div class="drop" id="drop'.$i.'"><div class="boxArt" id="'.$row['gameID'].'">'.$row['gameID'].'</div></div>';
}
else {
echo '<div class="drop" id="drop'.$i.'"></div>';
}
//close shelfrow div
if($i % 5 == 4) echo '</div>';
$i++;
}
//to complete the loop
$shelv_left = 5 - ($i % 5);
if($shelv_left < 5) {
for($j=0; $j < $shelv_left; $j++) {
echo '<div class="drop" id="drop'.($i+$j).'"></div>';
}
echo '</div>'; // end shelfrow div
}
...

How to submit multiple parameters in an HTML form on subsequent requests

I have a form that submits parameters using standard HTML controls to a PHP file. The PHP file then iterates through a csv file and returns the resuts via AJAX. If I select a dropdown menu from the form I get the data back no problem but when I then make another selection it doesn't remember what I have previously selected so only the new parameter gets submitted. How do I ensure the previous selected control(s) get submitted? Any ideas or suggestions greatly appreciated.
search.php:
<?php
error_reporting(E_ALL & ~E_NOTICE);
require_once('includes/MagicParser.php');
$key = $_GET['key'];
$search = $_GET['search'];
$counter = 0;
function recordHandler($record)
{
global $key;
global $search;
global $counter;
if ($record[$key] == $search) {
if ($counter % 2) {
print "<tr class=\"alt_row\">";
} else {
print "<tr>";
}
print "<td>".$record['Subject']."</td>";
print "<td>".$record['Tutor']."</td>";
print "<td>".$record['Level']."</td>";
print "<td>".$record['Course Type']."</td>";
print "<td>".$record['Course Code']."</td>";
print "<td>".$record['Primary Center']."</td>";
print "<td>".$record['Lesson 1 Date']."</td>";
print "<td></td>";
print "<td></td></td>";
print "</tr>";
} else {
return;
}
$counter ++;
}
print "
<table id=\"results\">
<tr>
<th>Subject</th>
<th>Tutor</th>
<th>Level</th>
<th>Type</th>
<th>Code</th>
<th>Center</th>
<th>Date</th>
<th>Timetable</th>
<th>Outline</th>
</tr>
";
MagicParser_parse("includes/course-data.csv", "recordHandler");
print "
</table>
<div id=\"pager_display\"></div>
";
?>
scripts.js:
function showCourse(search, key)
{
if (search == "") {
document.getElementById("dynamic_display").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("dynamic_display").innerHTML = xmlhttp.responseText;
pager = new Pager('results', 15);
pager.init();
pager.showPageNav('pager', 'pager_display');
pager.showPage(1);
}
}
xmlhttp.open("GET", "search.php?key="+ key +"&search=" + search, true);
xmlhttp.send();
}
/*
function disableEnableForm(form, boolean)
{
var formElements = form.elements;
for (i = 0; i < form.length; i ++) {
formElements[i].disabled = boolean;
}
}
*/
I would store them in $_SESSION. However, even once you get that squared away your basic search logic doesnt allow for multiple parameters so youll need to reconfigure that as well.. It might look something like the following:
if(isset($_SESSION['search']))
{
$search = $_SESSION['search'];
}
else
{
$search = array();
}
$key = $_GET['key'];
$search[$key] = $_GET['search'];
// store updated search in array
$_SESSION['search'] = $search;
$counter = 0;
function recordHandler($record)
{
global $key;
global $search;
global $counter;
foreach($search as $key => $value)
{
if($record[$key] != $value)
{
// if the record doesnt have all values that match for $key then its not a match
return;
}
}
if ($counter % 2) {
print "<tr class=\"alt_row\">";
} else {
print "<tr>";
}
print "<td>".$record['Subject']."</td>";
print "<td>".$record['Tutor']."</td>";
print "<td>".$record['Level']."</td>";
print "<td>".$record['Course Type']."</td>";
print "<td>".$record['Course Code']."</td>";
print "<td>".$record['Primary Center']."</td>";
print "<td>".$record['Lesson 1 Date']."</td>";
print "<td></td>";
print "<td></td></td>";
print "</tr>";
$counter ++;
}
This isnt by any means complete Im not sure exactly how your parser works and all that fun stuff - and this only supports an AND search - it will only return rows which match all supplied key-value pairs in the search. You would also need to implement something to clear the search parameters so the user can start over too. But you should be bale to get the basic idea...

Categories