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
Related
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
I am trying to write a program of photoalbums in simple PHP, but i want to make it a little more advanced then i used to do.
Usually i wrote it like this:
<?php $query = mysql_query("SELECT year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
$query2 = mysql_query("SELECT albumName, url FROM photo WHERE year = '".$year."'");
while($album = mysql_fetch_object($query2)){
echo "".$albumName."<br>";
}
} ?>
As you would understand it's really bad to have two while loops in one, so i want to do it differently. I want to learn how to do this better. The thing is, I don't know a name for this so it's difficult to search on this subject. Is there anyone able to hand me a snippet of code, a source or something to get me on the way?
Thank you so much.
You could do
<?php
$year = ''; // create a generic variable that will hold the album year
$query = mysql_query("SELECT albumName, url, year FROM photo ORDER BY year"); // Sort by year
while($album = mysql_fetch_object($query)) {
if($album->year != $year){ // check if $album->year is the same as the $year value
echo $album->year."<br>"; // if not the same echo the year
}
$year = $album->year; // set the $year value to the $album->year
echo "".$album->albumName."<br>";
}
?>
What if you do this:
<?php $query = mysql_query("SELECT albumName, url, year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
echo "".$albumName."<br>";
}
?>
What would be wrong?
Now your code might produce an album more than one times, if there are many albums per year.
I'm trying to create a dynamic list (5 row results) in php by first getting data from one table then using a resulting var to get the latest uploaded "image_links" (just 1 from each of the 5 artists) from another table -- then echo out.
The code here gives me the only one row with the latest image. When I comment out the "// get the latest image link uploaded ///" section of the code I get the 5 rows of different artists I really want but, of course, w/o images. I tried (among a bunch of things) mysql_result() w/o the while statement but that didn't work.
So what am I missing?
Thanks
Allen
//// first get the artists followed ////////////////
$QUERY= "SELECT * FROM followArtist WHERE user_id = $user_id ";
$res = mysql_query($QUERY);
$num = mysql_num_rows($res);
if($num>0){
while($row = mysql_fetch_array($res)){
$artist_name = $row['artist_name'];
$artist_id = $row['artist_id'];
$date_lastSent = $row['date_lastSent'];
$date_artPosted = $row['date_artPosted'];
$date_notePosted = $row['date_notePosted'];
//// get new notice data /////
if ($date_artPosted >= $date_lastSent) {
$artp = "new artwork posted";
}else{
$artp = "";
}
if ($date_notePosted >= $date_lastSent) {
$notep = "news/announcement posted";
}else{
$notep = "";
}
if ($artp!="" && $notep!="") {
$and = " and<br />";
}else{
$and = "";
}
if ($artp=="" && $notep=="") {
$no = "No new images or news posted since your<br /> last visit, but we'll let you know when there is.";
}else{
$no = "";
}
//////// get the latest image link uploaded ////////////////////////////////////
$QUERY2="SELECT image_link FROM artWork WHERE artist_id ='$artist_id' AND make_avail = '1' ";
//ORDER BY date_submit DESC
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 ){
while($row = mysql_fetch_assoc($res)){
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
//////// end of get the latest images uploaded ////////////////////////////////
echo "<tr align=\"center\" height=\"115px\">
<td align=\"left\" width=\"15%\"> <a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\">
<img src=slir/w115-h115/$path$image_link /></a></td>
<td align=\"center\" width=\"80%\"
<span class=\"deviceMedLtGrayFont\">$artist_name</span>
<br /><br />
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$artp</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$and$no</a>
<a href=\"process_artist_idImages.php?artist_id=$artist_id&search=search\"/>
$notep</a>
</td>
</tr>";
} //// end bracket for getting latest image link
} ///loop end for getting followed artist data
} ///end: if ($num>0) clause<code>
If I read your code correctly, I see you looping using data from query1 in the control structure, and a lookup on query2 within each loop. You are reusing the variables in your loop1 control structure for query2 ($num and the query handle ($res)) for the second loop. Probably not desirable within the loop.
You're sharing the variables $num and $res between the two queries ... your original properties will be overwritten when the second query is run. Use different property names for the inner query.
Example of problem:
$result = QueryA();
while( $row = $result->getRow() )
{
// -- You're overwriting the original result here ...
$result = QueryB();
// Next time the loop runs, it will run using the result from QueryB();
}
So change ...
$res = mysql_query($QUERY2);
$num = mysql_num_rows($res);
if($num>0 )
{
while($row = mysql_fetch_assoc($res))
{
mysql_fetch_assoc($res);
$image_link= $row['image_link'];
}
to
$res2 = mysql_query($QUERY2);
$num2 = mysql_num_rows($res2);
if($num2 > 0)
{
while($row2 = mysql_fetch_assoc($res2))
{
$image_link= $row2['image_link'];
}
this is a mess - as others have said you're using the same variables for different purposes.
That you're storing integers which seem to represent enumerations in a char field is bad.
You're iterating through the second result set to find the last record (from an unsorted result set!).
You only need one query - not 2.
SELECT f.artist_name, f.artist_id, f.dateLastSent....
SUBSTR(
MAX(
CONCAT(DATE_FORMAT(date_submit, '%Y%m%d%H%i%s'), a.image_link)
), 15) as img_link
FROM followArtist f
LEFT JOIN artWork a
ON (a.artist_id=f.artist_id AND a.make_avail = '1')
WHERE user_id = $user_id
GROUP BY f.artist_name, f.artist_id, f.dateLastSent....
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.
Here's what I've got so far-
$awards_sql_1 = mysql_query('SELECT * FROM categories WHERE section_id = 1') or die(mysql_error());
$awards_sql_2 = mysql_query('SELECT * FROM categories WHERE section_id = 2') or die(mysql_error());
$awards_sql_3 = mysql_query('SELECT * FROM categories WHERE section_id = 3') or die(mysql_error());
$awards_sql_4 = mysql_query('SELECT * FROM categories WHERE section_id = 4') or die(mysql_error());
$loop = 1;
while($row_sections = mysql_fetch_array($sections_query)) {
$category = 1;
echo "<h3>" . $row_sections['section_name'] . " (Loop# $loop)</h3>";
while($categories = mysql_fetch_array(${"awards_sql_{$loop}"})) {
${"winners_sql_{$loop}"} = mysql_query("SELECT * FROM 2009_RKR_bestof WHERE section = $loop && category = $category ORDER BY result_level ASC") or die(mysql_error());
echo "<h4><strong>{$categories['category_name']}</strong></h4>";
echo "<ul class=\"winners\">";
>> while($winners = mysql_fetch_array(${"winners_sql_{$loop}"})) {
switch ($winners['result_level']) {
case 1: $result_level = "Platinum"; break;
case 2: $result_level = "Gold"; break;
case 3: $result_level = "Silver"; break;
}
if (isset($winners['url'])) { $anchor = ""; $close = ""; }
echo "<li>$anchor{$winners['winner']}$close ($result_level)</li>";
unset($anchor);
unset($close);
}
echo "</ul>";
$category++;
}
$loop++;
}
Where I'm getting stumped, is I'm getting this thing to loop through correctly, my loop counter ($loop) is working, but when it gets time to spit out the actual reward recipients after the first loop through winners, it's only producing the category titles, the list-items are not getting looped out.
I added a little pointer to where I think the problem begins or centers around (>>).
My guess is I need to maybe unset a var somewhere, but I don't know, I can't see it.
I'm with KM - you're displaying a single page and with your loops, you've got a LOT of queries happening at once - what if 1,000 people hit that page at the same time? ouch...
Maybe consider a larger query (with some repeated data) and loop through it once?
For example:
SELECT
section_name,
category_name,
result_level,
url,
winner
FROM 2009_RKR_bestof
INNER JOIN categories ON 2009_RKR_bestof.category = categories.id
INNER JOIN sections ON 2009_RKR_bestof.section = sections.id
ORDER BY section_name,category_name ASC
In your loop, you can do checks to determine if you're in a new section (category/whatever):
//pseudo-code
$current_section = "";
while($stuff = mysql_fetch_array($sql))
{
if ($current_section == "")
{
$current_section = $stuff["section_name"];
}
if ($current_section == $stuff["section_name"])
{
//keep going in your loop
}
else
{
//we've gotten to a new section - so close your html and start a new section
}
}
You get the idea..
My guess would be that it is a data problem. It isn't having trouble reading the titles, only the winners. If it iterated once, I would check the data, and ensure that winners_sql_2 - winnders_sql_4 are getting actual data. Perhaps add an echo winners_sql_2 line, to output the contents of the query, and ensure the query is framed correctly.