HTML/PHP Syntax to Move to Next Record Button - php

I am developing on an HTML page a "go to next record" button.
Well, it goes to the next record once and then stops. Nothing happens when clicking on the "Prior Issue" button after the initial click. Since I increment the issue number, the cursor should move to the next record. I am only working on the "Prior Issue" button currently.
HTML syntax:
<a href="index.php?content=main_window&id=1" title="Show More Recent Issue" >< Next (Newer) Issue</a> &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp <a href="index.php?main_window&id=-1 title ="Show Older Issue" >Prior (Older)) Issue ></a>
The variable "id" is past to:
// Get Cycle Direction "1" stands for newer issue, "0" No Direction set, "-1" stands for older issue
if (!isset($_REQUEST['id']))
{$cycle_direction=0;
} else {
$cycle_direction = trim($_REQUEST['id']);
}
Which then gets past to: (only working on the "case -1" at this time.
switch(trim($cycle_direction))
{
case -1:
// display an older issue
echo "Decrement<br>";
$current_record_number=$current_record_number +1;
echo $current_record_number;
mysqli_data_seek($result, 0);
mysqli_data_seek($result, $current_record_number);
$row=mysqli_fetch_row($result);
printf ("%s \n",$row[0]);
$issuenum=$row[0];
break;
case 0:
// display current issue
//echo "No Selection";
break;
case 1:
// display newer issue
//echo "Increase";
$issuenum=2165;
break;
}

Do it right way. All what you need is url with next/prev record's ids.
$current_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
// in case you are using MySQL
$query = "SELECT
prev_id, next_id
FROM
(SELECT
id AS prev_id
FROM
issues
WHERE
id < $current_id
LIMIT 1) a,
(SELECT
id AS next_id
FROM
issues
WHERE
id > $current_id
LIMIT 1) b";
// fetch query data
$prev_id = ...
$next_id = ...
// SHOW CURRENT ISSUE
echo '<a href="index.php?content=main_window&id='.$next_id.'" title="Show More Recent Issue" >< Next (Newer) Issue</a> - <a href="index.php?main_window&id=$prev_id title ="Show Older Issue" >Prior (Older)) Issue ></a>';
In case you get your data from any other db, the logic is the same. Just select previous and next ids, and provide urls using $prev_id and $next_id.
Another solution using MAX/MIN trick.
$query = "SELECT
(SELECT MAX(id) FROM issues WHERE id < t.id) as prev_id,
(SELECT MIN(id) FROM issues WHERE id > t.id) as next_id
FROM issues t WHERE t.id = $current_id";

"Beta" version now working. I stripped the code down to the very bare essentials and added many echo statements to observe how the program responded. The short answer, PHP does not have a memory between each web-page so the values of the variables are "lost". While I was dimly aware of this, it did not become obvious for a while.
The solution was to develop a several $_SESSION variables to hold the array and to monitor the location of the cursor.
<?php
// Start the session
session_start();
include ("establish_array.php");
?>
The code below constitutes "establish_array.php" to establish the array in: "$_SESSION['result']".
<?php
require_once 'php_data/login_data.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the sfmags database server');
$query = "Select IssueIDNUM FROM tblIssueList ORDER by IssueDate DESC, IssueIDNUM ";
$_SESSION['result'] =$conn->query($query);
if (!$_SESSION['result']) die($conn->error);
$_SESSION['rowcount'] = mysqli_num_rows($_SESSION['result']);
?>
The code below is embedded in a case (switch) statement to move the magazine issue to the next older magazine when the pseudo "next" HTML key is pressed. The function "return_row_number();" returns the current row number, +1 is added to the row number and "mysqli_data_seek" is used to move to the next (older) record (issue).
$issuenum = $_SESSION['issuenum'];
$_SESSION['cursor_location'] = return_row_number();
echo "Cursor Location :" . $_SESSION['cursor_location'] . "<br>";
$_SESSION['cursor_location'] = $_SESSION['cursor_location'] + 1;
mysqli_data_seek($result, 0);
mysqli_data_seek($result,$_SESSION['cursor_location']);
$row=mysqli_fetch_row($result);
$issuenum=$row[0];
$_SESSION['issuenum'] = $issuenum;
echo "Issue Number: $issuenum <br>";
Thanks to: misunderstood, Unheiiig, and Alexander Ravikovich for providing useful advice and clues.

Update
This is what I got from your comment:
function return_row_number() {
// Loop through the Array; Get Row Number for the current issue global $result,$issuenum, $rowcount;
$count =0;
mysqli_data_seek($result, 0);
while($row=mysqli_fetch_array($result, MYSQL_ASSOC)) {
++$count;
if($issuenum == $row['IssueIDNUM']) {
return $count -1; break;
}
}
}
Now the mystery value is $issuenum.
And there is a terminology problem. This is not "Looping through an Array" it is querying the database and and looping through the query results.
This is a rather inefficient method of finding the next record. But before correcting that, you need to explain where the value for $issuenum is coming from.
It would also help to know more about the database table especially:
How many issue records?
What is the numbering scheme?
How often does a new issue get added?
end of update
With this line of code you will always get a value of 1
$current_record_number=$current_record_number +1;
because $current_record_number = 0.
You should add the current issue to the href where xx=current record #.
I changed "id" to "cycle"
added content= to Next href.
<a href="index.php?content=main_window&cycle=1&rec=xx"
title="Show More Recent Issue" > < Next (Newer) Issue</a>
&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp
<a href="index.php?content=main_window&cycle=-1&rec=xx
title ="Show Older Issue" >Prior (Older)) Issue ></a>
Then add this to your PHP:
$current_record_number = intval($_GET['rec']);
And change:
$cycle_direction = trim($_REQUEST['id']);
To:
$cycle_direction= intval($_GET['cycle']);
Instead of trim and isset you should just use intval()
$cycle_direction = intval($_REQUEST['id']);
Also instead of $current_record_number=$current_record_number +1;
You could use: $current_record_number += $cycle_direction
and eliminate the switch.
Unconventional approach
Let's say issues have values from 1 to 10.
$next[-1] = array(0,10,1,2,3,4,5,6,7,8,9,1);
$next[1] = array(0,2,3,4,5,6,7,8,9,10,1);
$next[0] = array(0,1,2,3,4,5,6,7,8,9,10);
$nextIssue = $next[intval($_REQUEST['id'])];
If issues are numbered 2001 to 2010
$nextIssue = 2000 + $next[intval($_REQUEST['id'])];
No matter how many issues you have there is no need to use a database.
Create the $next array as shown above, then save the array.
$fp = fopen('next.ser','w');
fwrite($fp,serialize($next));
fclose($fp);
When you need the $next array in an app use:
$next= unserialize(file_get_contents('next.ser'));

Related

Create a table with blank squares for missing mysql data

I've written a PHP script that can populate a table in a particular way so that multiple events (or no events) can be put in one square in an HTML - similar to the layout a calendar would have. But, there's a problem, the while statement I created to fill in squares in the table when there is no data doesn't detect when there is data, and fills the entire table with empty squares. This is what the output looks like (The page is styled using Bootstrap 3). From the mysql data I have provided, these events should be in the square at {Period 1, Monday}.
Here is my data in a mysql database; mysql data
Here is a snippet of the part of the page related to this table;
<?php
$query = "SELECT * FROM configtimetabletwo WHERE term = ".$term." AND week = ".$week." ORDER BY period, day LIMIT 100;";
$results = mysqli_query($conn, $query);
$pp=1; //The current y value of the table
$pd=0; //The current x value of the table
echo '<tr><td>';
while($row = mysqli_fetch_row($results)) {
while((pd!=$row[3] or $pp!=$row[4]) and $pp<6){ //This while statement fills in empty squares and numbers each row.
if($pd==0) {
echo $pp."</td><td>";
$pd++;
}
elseif($pd<5){
echo "</td><td>";
$pd++;
}
else {
echo "</td></tr><tr><td>";
$pd=0;
$pp++;
}
}
echo '<a href="?edit='.$row[0].'" class="label label-default">';
echo $row[5].' '.$row[6].' - '.$row[7]."</a><br>";
}
echo "</td></tr></table>"
?>
I haven't been able to figure out why this happens so far, thanks in advance to anyone who has any idea what's going on.
In the comments below my question, pavlovich pointed out the error. In this case, it was simply an issue of forgetting to use a $ to reference a variable. It would seem that this doesn't throw an error in a while statement like it would elsewhere.

PHP, looping through query results in SQL

I'm currently having trouble trying to create a loop for my desired outcome.
I'm currently creating a student record card which stores numerous data of different students (fake students).
I have created a query which returns the relevant data I need (see picture one, phpmyadmin)
SELECT mods.mid, mtitle, credits, enrl.ayr
FROM stud, smod, mods, enrl
WHERE stud.sid = '154279' AND stud.sid = smod.sid
AND smod.mid = mods.mid AND stud.sid = enrl.sid
ORDER BY `enrl`.`ayr` DESC
As you can see by the results, there are attributes:
mid
mtitle
credits
ayr
I have ordered by ayr in decending order. I am trying to make a loop that will run through the return on this query and print out each row until the end of whatever the current year is. Almost grouping all rows with the same year e.g. '2001/02' into a sub table which I can then name and print.
As you can see by my second picture of the student records page, I need to be able to print all records for the one year, then create a new header for the next existing year and print all containing rows for that.
{EDIT}
PHP Code:
$query = "SELECT mods.mid, mtitle, credits, enrl.ayr
FROM stud, smod, mods, enrl
WHERE stud.sid = '154279' AND stud.sid = smod.sid AND smod.mid = mods.mid AND stud.sid = enrl.sid
ORDER BY enrl.ayr DESC
";
$scap = '';
$curYear = $row['ayr'];
if($result = $link->query($query)) {
while ($row = $result->fetch_assoc() && $row['ayr'] == $curYear) {
$scap .= "<table id=\"test\" style=\"width:100%\">
<tr>
<td> " . $row['mid'] . " </td> <td> " . $row['mtitle'] . "</td> <td> " . $row['credits'] . " <td> " . $row['ayr'] . "</td>
</tr>
</table>";
}$result->free();
}
Thanks in advance.
Let's say you commit to one query max for the whole page. Like I said in comments
I would have a variable, call it $curYear. Start it out as some junk
string. In your loop, if the cur year thing is different than
$curYear, create a new segment in your output but regardless update
$curYear variable
That was not meant to interfere with your existing source code (that much). It is just a sentinel to alert you to a year change (year/term whatever).
So it starts as some junk value, like "797fsdf*"
Now inside your while, remember, you have ALL the years coming in from that result set for all years.
Do what I said in that pink block above comparing that variable $curYear to
$row['ayr']
When those two values are different, time to do whatever HTML treatment you want (creating a new html table, a new div, who cares). Let's call this the separation thing.
Regardless, after you output the row, make sure you have set $curYear to $row['ayr']. Why is that important? Because the next loop you want to know if you need to do the separation thing.
The tricky part is if you are doing html tables, you have to close out the previous table (prior year) if you are not on your first year

My array won't echo a value for some reason

I have a database that holds thousands of structures. The structures are searchable by choosing the "area" first, then selecting the "block_number". My first page allows the user to select the area, the area is then passed through the url to the next page. The next page uses php to pull up the blocks in that area. I'm trying to echo the "area" and "block_number" in the results. The my query works just fine but, for some reason I can't display the "area" in the results. See the code below.
<?
include("conn.php");
include("pl_header.php");
$area = mysql_real_escape_string($_GET['area']);
$wtf = '$area';
?>
<h3>Choose A Block Number in<br> <?=$area?></h3><br>
<center>
<?php
$tblWidth = 1;
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
$i = 1;
// Check to see if any results were returned
if(mysql_num_rows($sql) > 0){
echo '<div class="redBox extraIndent">';
// Loop through the results
while($row = mysql_fetch_array($sql)){
echo ''. $row['area'] .''. $row['block_number'] .'';
if($i == $tblWidth){
echo '';
$i = 0;
}
$i++;
}
echo '';
}else{
echo '<br>Sorry No Results';
}
?>
</div>
</body>
</html>
My issue is where you see '. $row['area'] .' displays nothing, but the '. $row['block_number'] .' works just fine.
Your query is only selecting block_number.
Try changing:
$sql = mysql_query("SELECT DISTINCT block_number FROM platform_locations WHERE area='$area'");
To:
$sql = mysql_query("SELECT DISTINCT block_number, area FROM platform_locations WHERE area='$area'");
Edit: If you have this issue in the future try var_dump($row); to see what the array contains. This would show you that you only have access to the block_number and not the area.
Double edit: I didn't notice, but the other answer is right about the $area var- you've already got the $area saved, use that variable instead of the return from the DB as it's already in memory. If this could change per record, it'd be prudent to use the record's area variable to make your code more reusable. However, in this particular case, your SQL statement has the area in the where clause, so it wont vary unless you attempt to use portions of this code elsewhere.
Your SQL query is only selecting block_number, so that's the only field that will be in the $row array. You've already got area as a variable $area so use that, not $row['area'].

show more button with PHP Mysql

I have a "show more" button to display 5 of last entries into database, with initial display of 1 record, like to change the initial variable to 3 results shown, here's my code:
$latest_entry_qry="SELECT *
FROM cityres
ORDER BY id DESC
LIMIT 0 , 5";
$latest_entry=mysql_query($latest_entry_qry);
?>
<div id="just-head"> <b>Recently Added:</b></div>
<div id="just-added">
<?
$modu = 1;
while($latest_entry_row=mysql_fetch_array($latest_entry))
{
if($modu%5 == 1)
$clsText = "";
else
$clsText = " class='show_more' style='display:none' ";
Here is a guess as your while loop is incomplete. I am assuming at the end there is a -
$modu++;
since you are checking $modu%5 == 1 every time in the while loop. if so, then you could just change it from
if($modu%5 == 1)
to
if($modu <=3)
Also, make note of #Daedalus comment about no longer using mysql_* functions

PHP & MySQL vote count problem?

I found this script on about.com which I'm trying to learn from on how to create a rating system but the script for some reason wont count a vote when the link is clicked and just reloads the page.
I was wondering how can I fix this problem? And what part of the code do I need to change and where?
Here is the full script below.
<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie])) {
echo "Sorry You have already ranked that site <p>";
} else {
//Otherwise, we set a cooking telling us they have now voted
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
echo "Your vote has been cast <p>";
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data )) {
//This outputs the sites name
echo "Name: " .$ratings['name']."<br>";
//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
$current = $ratings['total'] / $ratings['votes'];
} else {
$current = 0;
}
echo "Current Rating: " . round($current, 1) . "<br>";
//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
echo "Rank Me: ";
echo "Vote 1 | ";
echo "Vote 2 | ";
echo "Vote 3 | ";
echo "Vote 4 | ";
echo "Vote 5<p>";
}
?>
$mode is never set? While it may have worked if register globals was on, it is not on by default any more (and is removed in later versions of PHP)
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
Maybe you mean
if ( $_GET['mode']=="vote") {
The same goes for $id and $voted, which are also never set.
EDIT
I also would like to add, that if I went and changed id to 1';DROP TABLE vote; You would have a whole lot of data lost. Look at SQL Injection
EDIT
If the row in the table doesn't exist, you will need to INSERT it before you can UPDATE it.
I can also see $cookie is never set, looking at the code it should be 'Mysite' . $id. I added quotes for the string, though PHP will treat any unquoted text as string but avoid misunderstanding and errors later, its always a good idea.
Also this script assumes PHP option register_globals is on, you need to make that register_globals = ON in your php.ini

Categories