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

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

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.

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

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.

Infinite Scroll with MySQL Data

I have followed help located in this topic: Using infinite scroll w/ a MySQL Database
And have gotten close to getting this working properly. I have a page that is displayed in blocks using jquery masonry, in which the blocks are populated by data from a mysql database. When I scroll to the end of the page I successfully get the loading.gif image but immediately after the image it says "No more posts to show." which is what it should say if that were true. I am only calling in 5 posts initially out of about 10-15, so the rest of the posts should load when I reach the bottom of the page but I get the message that is supposed to come up when there really aren't any more posts.
Here is my javascript:
var loading = false;
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()) {
var h = $('.blockContainer').height();
var st = $(window).scrollTop();
var trigger = h - 250;
if((st >= 0.2*h) && (!loading) && (h > 500)){
loading = true;
$('div#ajaxLoader').html('<img src="images/loading.gif" name="HireStarts Loading" title="HireStarts Loading" />');
$('div#ajaxLoader').show();
$.ajax({
url: "blocks.php?lastid=" + $(".masonryBlock:last").attr("id"),
success: function(html){
if(html){
$(".blockContainer").append(html);
$('div#ajaxLoader').hide();
}else{
$('div#ajaxLoader').html('<center><b>No more posts to show.</b></center>');
}
}
});
}
}
});
Here is the php on the page the blocks are actually on. This page initially posts 5 items from the database. The javascript grabs the last posted id and sends that via ajax to the blocks.php script, which then uses the last posted id to grab the rest of the items from the database.
$allPosts = $link->query("/*qc=on*/SELECT * FROM all_posts ORDER BY post_id DESC LIMIT 5");
while($allRows = mysqli_fetch_assoc($allPosts)) {
$postID = $link->real_escape_string(intval($allRows['post_id']));
$isBlog = $link->real_escape_string(intval($allRows['blog']));
$isJob = $link->real_escape_string(intval($allRows['job']));
$isVid = $link->real_escape_string(intval($allRows['video']));
$itemID = $link->real_escape_string(intval($allRows['item_id']));
if($isBlog === '1') {
$query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
$result = $link->query($query);
while($blogRow = mysqli_fetch_assoc($result)) {
$blogID = $link->real_escape_string($blogRow['blog_id']);
$blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
$blogDate = $blogRow['pub_date'];
$blogPhoto = $link->real_escape_string($blogRow['image']);
$blogAuthor = $link->real_escape_string($blowRow['author']);
$blogContent = $link->real_escape_string($blogRow['content']);
//clean up the text
$blogTitle = stripslashes($blogTitle);
$blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));
echo "<div class='masonryBlock' id='".$postID."'>";
echo "<a href='post.php?id=".$blogID."'>";
echo "<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>";
echo "<strong>".$blogTitle."</strong>";
echo "<p>".$blogContent."</p>";
echo "</a>";
echo "</div>";
}
}
Here is the php from the blocks.php script that the AJAX calls:
//if there is a query in the URL
if(isset($_GET['lastid'])) {
//get the starting ID from the URL
$startID = $link->real_escape_string(intval($_GET['lastid']));
//make the query, querying 25 fields per run
$result = $link->query("SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".$startID."', 25");
$html = '';
//put the table rows into variables
while($allRows = mysqli_fetch_assoc($result)) {
$postID = $link->real_escape_string(intval($allRows['post_id']));
$isBlog = $link->real_escape_string(intval($allRows['blog']));
$isJob = $link->real_escape_string(intval($allRows['job']));
$isVid = $link->real_escape_string(intval($allRows['video']));
$itemID = $link->real_escape_string(intval($allRows['item_id']));
//if the entry is a blog
if($isBlog === '1') {
$query = "SELECT * FROM blogs WHERE blog_id = '".$itemID."' ORDER BY blog_id DESC";
$result = $link->query($query);
while($blogRow = mysqli_fetch_assoc($result)) {
$blogID = $link->real_escape_string($blogRow['blog_id']);
$blogTitle = $link->real_escape_string(html_entity_decode($blogRow['blog_title']));
$blogDate = $blogRow['pub_date'];
$blogPhoto = $link->real_escape_string($blogRow['image']);
$blogAuthor = $link->real_escape_string($blowRow['author']);
$blogContent = $link->real_escape_string($blogRow['content']);
$blogTitle = stripslashes($blogTitle);
$blogContent = html_entity_decode(stripslashes(truncate($blogContent, 150)));
$html .="<div class='masonryBlock' id='".$postID."'>
<a href='post.php?id=".$blogID."'>
<div class='imgholder'><img src='uploads/blogs/photos/".$blogPhoto."'></div>
<strong>".$blogTitle."</strong>
<p>".$blogContent."</p>
</a></div>";
}
}
echo $html;
}
I have tried using the jquery infinite-scroll plugin, but it seemed much more difficult to do it that way. I don't know what the issue is here. I have added alerts and did testing and the javascript script is fully processing, so it must be with blocks.php right?
EDIT: I have made a temporary fix to this issue by changing the sql query to SELECT * FROM all_posts WHERE post_id < '".$startID."' ORDER BY post_id DESC LIMIT 15
The blocks are now loading via ajax, however they are only loading one block at a time. The ajax is sending a request for every single block and they are fading in one after another, is it possible to make them all fade in at once with jquery masonry?
I seen your code in another answer, and I would recommend using the LIMIT functionality in MySql instead of offsetting the values. Example:
SELECT * FROM all_posts ORDER BY post_id DESC LIMIT '".(((int)$page)*5)."',5
This will just take a page number in the AJAX request and get the offset automatically. It's one consistent query, and works independent of the last results on the page. Send something like page=1 or page=2 in your jQuery code. This can be done a couple different ways.
First, count the number of elements constructed on the page and divide by the number on the page. This will yield a page number.
Second, you can use jQuery and bind the current page number to the body:
$(body).data('page', 1)
Increment it by one each page load.
Doing this is really the better way to go, because it uses one query for all of the operations, and doesn't require a whole lot of information about the data already on the page.
Only thing to note is that this logic requires the first page request to be 0, not 1. This is because 1*5 will evaluate to 5, skipping the first 5 rows. If its 0, it will evaluate to 0*5 and skip the first 0 rows (since 0*5 is 0).
Let me know any questions you have!
Have you tried doing any debugging?
If you are not already using, I would recommend getting the firebug plugin.
Does the ajax call return empty? If it does, try echoing the sql and verify that is the correct statement and that all the variables contain the expected information. A lot of things could fail considering there's a lot of communication happening between client, server and db.
In response to your comment, you are adding the html in this piece of code:
if(html){
$(".blockContainer").append(html);
$('div#ajaxLoader').hide();
}
I would do a console.log(html) and console.log($(".blockContainer").length) before the if statement.

Issues with dynamically generated web pages

Please I need your help with my script. I'm puting a link to old news articles in a sidebar and making it clickable. The page it's coming from (header.php) has the GET id in the URL, so the page receiving it also checks for the value of the GET. It displays fine when I click the old news article in the sidebar.
The problem I'm having is that, whenever I want to view the current article on the the About.php page I get Undefined Index id
Please how can I solve this issue, so that my script works well for displaying old articles and also the current news article.
Thanks
about.php
<?php
$id = $_GET['id'];
$past = mysql_query( "SELECT * FROM about WHERE about_id = '".$id."'") or die(mysql_error());
$row = mysql_fetch_array($past);
echo "<h2>";
echo $row1['about_head'];
echo "</h2>";
echo "<p>";
echo $row1['about_content'];
echo "</p>";
?>
Header
<?php
$past = mysql_query("SELECT * FROM about") or die(mysql_error());
while($row = mysql_fetch_array($past))
echo " $row[about_head].<br/>";
?>
When you have this code:
$id = $_GET['id'];
you are retriving an item called "id" from the array called $_GET (which holds all GET parameters). However when this parameter "id" is not present, PHP emits a warning. To get rid of it, replace the line with:
$id = "";
if (isset($_GET["id"])) $id = $_GET["id"];
or shortly:
$id = isset($_GET["id"]) ? $_GET["id"] : "";
which first asks whether the parameter is present, and if it's not, gives an empty string. If you expect the $id variable to be an integer, you might instead want to use zero instead of an empty string:
$id = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
this also casts the passed parameter to "int", so you have a guarantee that it is not a string (possibly containing malicious data).
Something like this should work:
if( array_key_exists( 'id', $_GET ) )
{
//do your code in here
}
else
{
//fallback to scenario in which $_GET['id'] isn't set in the url
}

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