How Can I send $_POST with query string in a link - php

This is php code which checks if form(on same page) is posted and gets the result depending upon $_POST array if it is posted or returns all results from data base. this also sets $total variable containing number_of_pages later used for pagination
if(!isset($_POST['search']))
{
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "select SQL_CALC_FOUND_ROWS * from feedbacks order by Date desc limit $id, 10 ";
}
else if (!empty($_POST['from']))
{
$timstmp = strtotime($_POST['from']);
$dt = date("Y-m-d H:i:s", $timstmp);
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM `feedbacks` WHERE `Date` >= \"$dt\" order by Date desc limit $id, 10 ";
}
else if (!empty($_POST['name']))
{
$name = '%'.$_POST['name'].'%';
$id = (isset($_GET['id']) ? $_GET['id'].'0' : 10);
$id = $id-10;
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM `feedbacks` WHERE `name` LIKE '$name' order by Date desc limit $id, 10 ";
}
$result= mysqli_query($connection, $query);
$r = mysqli_fetch_array(mysqli_query($connection, 'SELECT FOUND_ROWS()'));
$total = ceil($r['FOUND_ROWS()']/10);
$feedbacks = array();
for ($i = 0;$row= mysqli_fetch_assoc($result); $i++)
{
$feedbacks[$i] = new FeedBack($row);
}
?>
These are the html links that are automatically generated depending upon the total number of pages which is calculated depending upon results from data base
<?php
if ($total>1)
{ ?> <div class="pagging">
<?php for( $i=$total; $i>=1; $i--)
{ ?>
<div class="right">
<a id="pagination" href="index.php?id=<?php echo $i; ?>"><?php echo $i; ?></a>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<!-- Table -->
On this page I'm implementing filters. User input data in the form and press search so depending upon the $_POST array the different results are loaded and variable $total containing num_of_pages is modified as the 1st block of php code shows now the first page displays 1st 10 results from data base using offset 0 or ofset = IDX10-10 if id is set but problem is that it only works for default results i.e when all results are displayed and filter is not applied but when user searches through a filtered 1st 10 filtered results are displayed but when user clicks the next page it does not work because $_POST is unset which was checked by the php If conditions in above php code. so my question is how can i send $_POST[] along with the id to make it work. Any help would be appreciated. Thanks.

You can't send POST variables through a link. You need to use GET.
Link
//the link will reflect some_page.php?name1=value1&name2=value2...etc
On the PHP side use the $_GET or $_REQUEST variable, instead of $_POST.

Related

how do i add a page indicator like "Question 1 of 10"?

How can i add something like this to my quizzer page indicator I've been searching and trying for a couple of days i couldn't figure this out.
total question
<?php
//total question
$db = new db;
$link = $db->dbconnect();
$iauid = $_SESSION["uid"];
$qizid = $_SESSION["qizid"];
$qry = "SELECT COUNT qcatid FROM AS total FROM tbcat";
$result = mysqli_query($link, $qry) or die (mysqli_error($link));
$row = mysqli_fetch_array($result);
echo $row['total'];
?>
<label id="numberIndicator">1</label>
<?php
page indicator
<script type="text/javascript">
//page indicator
function add() {
var quantity_temp = document.getElementById("numberIndicator").innerText;
var quantity_int = parseInt(quantity_temp, 10) + 1;
document.getElementById("numberIndicator").innerHTML = quantity_int.toString();
}
</script>
it should be like this
First of all, your query looks wrong:
$qry = "SELECT COUNT qcatid FROM AS total FROM tbcat";
Should be more like this (since COUNT is a function)
$qry = "SELECT COUNT(qcatid) total FROM tbcat";
Well, the simplest way starting from the code you posted would be something like this (in your PHP):
Question <label id="currentPageIndicator"><?=$currentPage?></label> of <label id="totalPageIndicator"><?=$row['total']?></label>
Where $currentPage would be assigned a default of 1 and would either be stored in session or would be calculated by current row selection from your query that fetches data or something in that direction.

PHP selecting next array value of same id within the same page

Sorry if I asked a dumb question, quite new to PHP. I wanted to select the next array value within the same page and the same id, as all of them are from the same id. Mind if I ask for any help on this code? Thanks!
<?php
//get the id from the view page / search page e.g. url?id=1
$_SESSION['id'] = $_GET['id'];
$id = $_SESSION['id'];
include "backend/connect.php";
$sqlquestion = "Select * from game_question where game_id_fk = $id";
$result = mysqli_query($conn,$sqlquestion);
if(mysqli_num_rows($result)<=0){
echo "<script>alert('No questions found!');</script>";
}
while($row = mysqli_fetch_array($result)){
$question[] = $row['game_question'];
$qid[] = $row['game_question_id'];
}
?>
<?php
$current_index = array_search($qid, $question);
$next = $current_index + 1;
$prev = $current_index - 1;
?>
<?php if ($prev > 0): ?>
Previous
<?php endif; ?>
<?php if ($next < count($question)): ?>
Next
<?php endif; ?>
This is the table schema of game_question
WARNING
Concatenating query params into query string may lead to SQL injection, take a look here
A simple way to do that is to implement some sort of pagination, in which each page is exactly 1 item long, and pass the current page as a GET param.
You can implement it as a LIMIT clause on your query, like this:
$pos = (isset($_GET['pos']) && $_GET['pos']) ? $_GET['pos'] : 0;
$sqlquestion = "
Select *
from game_question
where game_id_fk = $id
LIMIT 1 OFFSET $pos
";
Then you have to calculare previous and next position based on the $pos variable and add them in the links as a query param, like url.php?id=1&pos=3;
Note that this way positions starts at 0
I would take an approach of querying the DB only once, so i assume the amount of questions belonging to one id is not too huge.
This way you can retrieve all the results and then use some front end magic to display these results with next/prev functionality. I wrote a sample where jQuery has your questions, so its up to you how you want to display them.
You can also look at Bootstrap (https://getbootstrap.com/), it has some cool features, so you could get PHP to loop your questions and write the HTML elements, then Bootstrap would do its magic displaying it
I've also added parameter binding to your query, this will prevent some SQL injections and should always be used
<?php
//get the id from the view page / search page e.g. url?id=1
$id = $_SESSION['id'] = $_GET['id'];
include "backend/connect.php";
$stmt = mysqli_prepare($con, "SELECT * FROM game_question WHERE game_id_fk = ?");
mysqli_stmt_bind_param($stmt, "s", $id);
$result = mysqli_stmt_execute($stmt);
$questions = array();
if(mysqli_num_rows($result)<=0){
echo "<script>alert('No questions found!');</script>";
die;
}
while($row = mysqli_fetch_array($result)){
$questions[$row['game_question_id']] = $row['game_question'];
}
?>
<!-- HTML -->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var questions = <?php echo json_encode($questions) ?>;
$.each(questions, function (i, elem) {
// do your stuff
});
</script>
</head>
<body>
</body>
Here's an example of bootstrap tabs with prev/next buttons: https://codepen.io/techiegang/pen/QjdgJJ

PHP List Menu Boxes - Best way to do the cycle?

This is part of code from my backoffice page. ( is an edit.php page for a user to edit / modify )
// first query to get cats from user table
$query = "select * from user where name='".$_SESSION['username']."' order by id ASC limit 1";
$result=mysql_query($query);
if (mysql_num_rows($result)) {
while($row=mysql_fetch_array($result)){
$cat1 = $row['cat1'];
$cat2 = $row['cat2'];
$cat3 = $row['cat3'];
$cat4 = $row['cat4'];
$cat5 = $row['cat5'];
$cat6 = $row['cat6'];
$cat7 = $row['cat7'];
$cat8 = $row['cat8'];
$cat9 = $row['cat9'];
$cat10 = $row['cat10'];
}
}
// now i want to build 10 select boxes with selected according the user table $cats
// below is what i can build to first box $cat1
// is there a way i can produce this for the 10 select boxes whitout having to make 10 cycles of bellow code
<select name="theme" id="theme">
<?php
$q1 = 'SELECT * FROM cats ORDER BY title ASC';
$r1 = mysql_query($q1);
while( $row = mysql_fetch_array($r1)) {
if ( $cat1 == $row['id'] ) {
print "<option class=\"cssoption\" selected=\"selected\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
else {
print "<option class=\"cssoption\" value=\"".$row['id']."\">".htmlentities($row['title'])."</option>";
}
}
?>
</select>
I am not a coder so this might not be effective code.
Hope someone can help me here and understands what i am trying to do.
Many Thanks.
The code is fine. This 10 cycles as you name it is a almost zero cost.
This is the usual way we do it, we fetch sequentialy the records one by one.
In addition it makes no sense to ask not to do the 10 cycles because you are applying an if else condition in the same time, this means that you check every record if the cat id is the same with the row so you need the loop.
On the other hand if for some reason you want to skip some records, you can use the mysql seek function to start fetching from the desired record.
for($i=0;$i<99999;$i++)
(9999*9999);
echo 'This time the cost of this loop was:',(microtime()-$start),' seconds.';
?>

How do I add a filter button to this pagination?

Hey, I want to add a button(link), that when clicked will filter the pagination results.
I'm new to php (and programming in general) and would like to add a button like 'Automotive' and when clicked it updates the 2 mysql queries in my pagination script, seen here:
As you can see, the category automotive is hardcoded in, I want it to be dynamic, so when a link is clicked it places whatever the id or class is in the category part of the query.
1:
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='automotive'"));
2:
$get = mysql_query("SELECT * FROM explore WHERE category='automotive' LIMIT $start, $per_page");
This is the entire current php pagination script that I am using:
<?php
//connecting to the database
$error = "Could not connect to the database";
mysql_connect('localhost','root','root') or die($error);
mysql_select_db('ajax_demo') or die($error);
//max displayed per page
$per_page = 2;
//get start variable
$start = $_GET['start'];
//count records
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='automotive'"));
//count max pages
$max_pages = $record_count / $per_page; //may come out as decimal
if (!$start)
$start = 0;
//display data
$get = mysql_query("SELECT * FROM explore WHERE category='automotive' LIMIT $start, $per_page");
while ($row = mysql_fetch_assoc($get))
{
// get data
$name = $row['id'];
$age = $row['site_name'];
echo $name." (".$age.")<br />";
}
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
//show prev button
if (!($start<=0))
echo "<a href='pagi_test.php?start=$prev'>Prev</a> ";
//show page numbers
//set variable for first page
$i=1;
for ($x=0;$x<$record_count;$x=$x+$per_page)
{
if ($start!=$x)
echo " <a href='pagi_test.php?start=$x'>$i</a> ";
else
echo " <a href='pagi_test.php?start=$x'><b>$i</b></a> ";
$i++;
}
//show next button
if (!($start>=$record_count-$per_page))
echo " <a href='pagi_test.php?start=$next'>Next</a>";
?>
Example with 2 links/categories:
<a href='script.php?category=automotive'>automotive</a> <a href='script.php?category=sports'>sports</a>
Inside script.php:
$category = mysql_real_escape_string($_GET['category']);
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='$category'"));
...
$get = mysql_query("SELECT * FROM explore WHERE category='$category' LIMIT $start, $per_page");
Edit: I only posted this answer in response to the OP stating he was new to programming. Good hygiene is learned at the beginning very easily and becomes habit, or much later and is very hard to make habit.
http://us2.php.net/manual/en/security.database.sql-injection.php
please also read this article on security for databases. It would be much improved to write your queries as:
$start = mysql_real_escape_string($_GET['start']);
settype($start, 'integer');
$category = mysql_real_escape_string($_GET['category']);
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='%s'", $category));
...
$get = mysql_query("SELECT * FROM explore WHERE category='%s' LIMIT %d, %d", $category, $start, $per_page);
It is always worth it to write the extra secure code, even if just for practice. Basic security rules for databases are: Never trust user input, always check generated output. Since the input is from a querystring and gets run against the database, it has to be filtered.

Associate different data

I will try to be as clear as possible because I can't get anybody to help me around,
I am trying to associate some data from a 'videos' table with their respective ID.
Lets say, I have column ID, title, serie, season, episode.
I am getting my data :
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
?>
(that is in the page where you see the video itself)
So now I can get the number of episodes from a serie and season.
What I'm trying to do is have a link for the next episode, and aa link for the previous one. In the URL I am working with the id, so http://website.com/view/id/'video id here'/
So how can I get the ID of the following and previous episodes of the same season AND serie?
Help will be much appreciated!
The easiest thing I thought of is
<?=$row['id'] + 1?>
<?=$row['id'] - 1?>
But the thing is that it's mixed videos, so it wont work 100%
I think you've taken my example too literally. I'll post a complete example in the morning (I'm just replying from my iPhone at the mo). For some reason it wouldn't let me add a comment to your last reply, so sorry this is as an answer.
[edit] here's a more complete example:
<?php
$result = mysql_query("SELECT * FROM videos WHERE series='$series' AND season = '$season'");
$last_row = null;
$next_row = null;
$current_id = $_GET['id'];
while($row = mysql_fetch_assoc($result)) {
if($current_id == $row['id']) {
$next_row = mysql_fetch_assoc($result);
break;
}
$last_row = $row;
}
if($last_row != null) {
echo "<a href='?id={$last_row['id']}'>Prev</><br/>\n";
}
if($next_row != null) {
echo "<a href='?id={$next_row['id']}'>Next</><br/>\n";
}
?>
A few things to note:
This is untested.
In your initial example, I didn't know where you were getting the $row['serie'] and $row['season'], so in my example, I've just used the variables $series and $season. You'll have to fill these in with what you want the current result set to be filtered by.
For my example, the URL format uses the GET layout (ie. ?id=).
If you do:
$results = mysql_query($sql);
(where $sql is your mentioned select statement)
Then the $results array will contain all results of that series/season.
So you can access it via:
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
Note that you'll of course need to check that $n - 1 isn't less than zero, and ($n + 1) isn't greater than your $total_rows.
Here is what I tried, I guess it is what you meant,
All that it's doing is put the previous episode, so I get /view/id/3/ (if the episode i am watching is 4)
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
?>
<? if($row['episode'] == 1) { ?>
<td align="center" width="33%"></td>
<? } else { ?>
<td align="center" width="33%"><img src="images/previous.gif" srcover="images/previoush.gif" alt="Previous Video" border="0" /></td><? } ?>
That is only for the previous one,
Sorry I had to post like this, if not it wouldnt have appeared correctly,
(Correct me if I'm wrong with the code)
And thanks for the reply

Categories