Pagination in PHP - page links - php

Thank you everyone who helped me yesterday with this new to me topic.
I've tried to write code myself, and it works fine for the first page.
However, when I click any of the page links, I get this:
The requested URL /headfirst_phpmysql/guitarwars/index.php&page=3 was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
Here is my entire PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guitar Wars - High Scores</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h2>Guitar Wars - High Scores</h2>
<p>Welcome, Guitar Warrior, do you have what it takes to crack the high score list? If
so, just add your own score.</p>
<hr />
<?php
// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "Previous" link
if ($cur_page > 1) {
$page_links .= '<a href = "' . $_SERVER['PHP_SELF'] .
'&page=' . ($cur_page - 1) . '"><-</a>';
}
else {
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= '' . $i;
}
else {
$page_links .= '<a href = "' . $_SERVER['PHP_SELF'] .
'&page=' . $i . '"> ' . $i . '</a>';
}
}
// If this page is not the last page, generate the "Next" link
if ($cur_page < $num_pages) {
$page_links .= '<a href = "' . $_SERVER['PHP_SELF'] .
'&page=' . ($cur_page + 1) . '">-></a>';
}
else {
$page_links .= '->';
}
return $page_links;
}
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
// Number of results per page
$results_per_page = 5;
// Compute the number of the first row on the page
$skip = (($cur_page - 1) * $results_per_page);
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Retrieve the score data from MySQL
$query = "SELECT * FROM guitarwars WHERE approved = 1 ORDER BY score DESC, date ASC";
$data = mysqli_query($dbc, $query);
$total = mysqli_num_rows($data);
$num_pages = ceil($total / $results_per_page);
// Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
$data = mysqli_query($dbc, $query);
// Loop through the array of score data, formatting it as HTML
echo '<table>';
$i = 0;
while ($row = mysqli_fetch_array($data)) {
// Display the score data
if ($i == 0) {
echo '<tr><td colspan="2" class="topscoreheader">Top Score: ' . $row['score'] . '</td></tr>';
}
echo '<tr><td class="scoreinfo">';
echo '<span class="score">' . $row['score'] . '</span><br />';
echo '<strong>Name:</strong> ' . $row['name'] . '<br />';
echo '<strong>Date:</strong> ' . $row['date'] . '</td>';
if (is_file(GW_UPLOADPATH . $row['screenshot']) && filesize(GW_UPLOADPATH . $row['screenshot']) > 0) {
echo '<td><img src="' . GW_UPLOADPATH . $row['screenshot'] . '" alt="Score image" /></td></tr>';
}
else {
echo '<td><img src="' . GW_UPLOADPATH . 'unverified.gif' . '" alt="Unverified score" /></td></tr>';
}
$i++;
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($cur_page, $num_pages);
}
mysqli_close($dbc);
?>
</body>
</html>

Where is your ? in query string? ;)
And the long answer:
The server is not requesting the index.php file but index.php&page=3. So it returns 404 as it's not finding anything;)

The first argument suplied by GET is introduced with an ?. If you have multiple arguments supplied, you use the & after that:
testurl.html?firstarg=123&second_arg=456

Use http_build_query to construct the query string. See the docs # http://www.php.net/manual/en/function.http-build-query.php
You need to append the result to http://example.com/? (note the ?)

Try to use this:
(added ? before &)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guitar Wars - High Scores</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h2>Guitar Wars - High Scores</h2>
<p>Welcome, Guitar Warrior, do you have what it takes to crack the high score list? If
so, just add your own score.</p>
<hr />
<?php
// This function builds navigational page links based on the current page and the number of pages
function generate_page_links($cur_page, $num_pages) {
$page_links = '';
// If this page is not the first page, generate the "Previous" link
if ($cur_page > 1) {
$page_links .= '<a href = "' . $_SERVER['PHP_SELF'] .
'?&page=' . ($cur_page - 1) . '"><-</a>';
}
else {
$page_links .= '<- ';
}
// Loop through the pages generating the page number links
for ($i = 1; $i <= $num_pages; $i++) {
if ($cur_page == $i) {
$page_links .= '' . $i;
}
else {
$page_links .= '<a href = "' . $_SERVER['PHP_SELF'] .
'?&page=' . $i . '"> ' . $i . '</a>';
}
}
// If this page is not the last page, generate the "Next" link
if ($cur_page < $num_pages) {
$page_links .= '<a href = "' . $_SERVER['PHP_SELF'] .
'?&page=' . ($cur_page + 1) . '">-></a>';
}
else {
$page_links .= '->';
}
return $page_links;
}
// Calculate pagination information
$cur_page = isset($_GET['page']) ? $_GET['page'] : 1;
// Number of results per page
$results_per_page = 5;
// Compute the number of the first row on the page
$skip = (($cur_page - 1) * $results_per_page);
require_once('appvars.php');
require_once('connectvars.php');
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Retrieve the score data from MySQL
$query = "SELECT * FROM guitarwars WHERE approved = 1 ORDER BY score DESC, date ASC";
$data = mysqli_query($dbc, $query);
$total = mysqli_num_rows($data);
$num_pages = ceil($total / $results_per_page);
// Query again to get just the subset of results
$query = $query . " LIMIT $skip, $results_per_page";
$data = mysqli_query($dbc, $query);
// Loop through the array of score data, formatting it as HTML
echo '<table>';
$i = 0;
while ($row = mysqli_fetch_array($data)) {
// Display the score data
if ($i == 0) {
echo '<tr><td colspan="2" class="topscoreheader">Top Score: ' . $row['score'] . '</td></tr>';
}
echo '<tr><td class="scoreinfo">';
echo '<span class="score">' . $row['score'] . '</span><br />';
echo '<strong>Name:</strong> ' . $row['name'] . '<br />';
echo '<strong>Date:</strong> ' . $row['date'] . '</td>';
if (is_file(GW_UPLOADPATH . $row['screenshot']) && filesize(GW_UPLOADPATH . $row['screenshot']) > 0) {
echo '<td><img src="' . GW_UPLOADPATH . $row['screenshot'] . '" alt="Score image" /></td></tr>';
}
else {
echo '<td><img src="' . GW_UPLOADPATH . 'unverified.gif' . '" alt="Unverified score" /></td></tr>';
}
$i++;
}
echo '</table>';
// Generate navigational page links if we have more than one page
if ($num_pages > 1) {
echo generate_page_links($cur_page, $num_pages);
}
mysqli_close($dbc);
?>
</body>
</html>

Related

Search results in a table cause out of place data in table.

Hello guys I'm having trouble with this script I made. Any time I use the search bar to search for data on my website in a table form the first row always come back perfectly with the data in tact but any thing after the first row all the data falls out of place in the other rows. I was able to do this perfectly in non-table structure situations so I don't know why this is doing this I need help how I can keep all the data intact.
Screen Shot
<?php
//SEARCHX
include("hidden_path/mysqli/procedural/session/session_crud/v1/0/instructions/php/session_and_connection.php");
$output = ' ';
if(isset($_GET['search']) && $_GET['search'] !== ' ') {
$user_input = $_GET['search'];
if ($user_input === "") {
header('Location: '.$_SERVER['PHP_SELF']);
die;
}
//PAGINATION
$user_input = $_GET['search'];
$and = "&";
$pagevx = "page=";
//SEARCHX
$user_input = trim(" $user_input ");
$user_input = preg_replace('/\s+/', ' ', $user_input);
$user_input = mysqli_real_escape_string($connect, $user_input);
$user_input = htmlspecialchars($user_input);
//PAGINATION
$page = mysqli_query($connect, "SELECT COUNT(*) FROM posts WHERE post_title LIKE '%$user_input%' OR post_content LIKE '%$user_input%'");
// total row count
$row = mysqli_fetch_row($page);
$rows = $row[0];
// results displayed per page
$page_rows = 2;
// page number of last page
$last = ceil($rows/$page_rows);
// makes sure $last cannot be less than 1
if($last < 1) {
$last = 1;
}
// page num
$pagenum = 1;
// get pagenum from URL if it is present otherwise it is 1
if(isset($_GET['page'])) {
$pagenum = preg_replace('#[^0-9]#', '', $_GET['page']);
}
// makes sure the page number isn't below 1, or more then our $last page
if($pagenum < 1) {
$pagenum = 1;
}
else if($pagenum > $last) {
$pagenum = $last;
}
// set the rage of rows to query for the chosen $pagenum
$limit = 'LIMIT ' . ($pagenum - 1) * $page_rows . ',' . $page_rows;
$page = mysqli_query($connect, "SELECT * FROM posts WHERE post_title LIKE '%$user_input%' OR post_content LIKE '%$user_input%' ORDER BY post_id DESC $limit");
// establish $paginationCtrls variable
$paginationCtrls = '';
// if more the 1 page
if($last != 1) {
if($pagenum > 1) {
$previous = $pagenum - 1;
$paginationCtrls .= '<span class="pag_back_arrow"; style="text-decoration: none;"><</span> ';
// Render clickable number links
for($i = $pagenum - 4; $i < $pagenum; $i++) {
if($i > 0) {
$paginationCtrls .= ''.$i.' ';
}
}
}
// render the target page number without a link
$paginationCtrls .= ''. $pagenum . ' ';
// render clickable number links that appear on the right
for($i = $pagenum + 1; $i < $last; $i++) {
$paginationCtrls .= ''.$i.' ';
// allows up to 4 pages
if($i >= $pagenum + 4) {
break;
}
}
if($pagenum != $last) {
$next = $pagenum + 1;
$paginationCtrls .= ' <span class="pag_next_arrow"; style="text-decoration: none;">></span> ';
}
}
//SEARCHX
?>
<!DOCTYPE html>
<html>
<head>
<title>
Results
</title>
</head>
<meta name="viewport" content="width=device-width">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="0/instructions/css/query/desktop.css">
<link rel="stylesheet" type="text/css" href="0/instructions/css/query/mobile.css">
<body>
<?php
//SEARCHX
$c = mysqli_num_rows($page);
if($c == 0) {
$output = '<h2 class="no_results_error_message";><span style="color: red;">No results for: </span><b><span style="color: white;">' . $user_input . '</span></h2></b>';
} else {
?>
<div class="result_section";>
<h2><span class="for_headline">Results For: </span><span id="result_output"><?php $outputx = "$user_input"; print("$outputx"); ?></span></h2>
</div>
<!-- Search Box -->
<?php include("search_box.php"); ?> <br>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>user_id</td>
<td>topic_id</td>
<td>post_title</td>
<td>post_content</td>
<td>post_date</td>
<td>Update</td>
</tr>
<?php
// shows the user what page they are on, and the total number of pages
$textline1 = "Search_i";
$textline2 = "Page <b>$pagenum</b> of <b>$last</b>";
while($row = mysqli_fetch_array($page, MYSQLI_ASSOC)) {
echo "<tr>";
echo "<td>".$row['user_id']."</td>";
echo "<td>".$row['topic_id']."</td>";
echo "<td>".$row['post_title']."</td>";
echo "<td>".$row['post_content']."</td>";
echo "<td>".$row['post_date']."</td>";
echo "<td>Edit | Delete</td></table>";
?>
<?php
$output .= '<a href="' . $link . '">
</a>';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($connect);
?>
<!-- PAGINATION -->
<!--shows the user what page they are on, and the total number of pages -->
<p><?php //echo $textline1 = "Search_i"; ?></p>
<p id="page_of";><?php //echo $textline2; ?></p>
<div class="pagination_controls"><?php echo $paginationCtrls; ?></div>
</body>
</html>
you are closing table in loop. Change your code with
while ($row = mysqli_fetch_array($page, MYSQLI_ASSOC)) {
echo "<tr>";
echo "<td>" . $row['user_id'] . "</td>";
echo "<td>" . $row['topic_id'] . "</td>";
echo "<td>" . $row['post_title'] . "</td>";
echo "<td>" . $row['post_content'] . "</td>";
echo "<td>" . $row['post_date'] . "</td>";
echo "<td>Edit | Delete</td></tr>";
}
</table> //close table after loop

How do i define from which table that specific column comes from?

I made a page in which one can edit the prices for each article that each webshop has. The price that it already has is in the textfield and it can be changed to whatever the user may want. Then the user hits the Edit (Wijzigen is Dutch for Edit) button and it should change to whatever was in the textfield before pressing it.
But I'm having quite some trouble with the UPDATE query since I need to give it some ID's to select the right one. And, as you'll be able to see in the source, right after starting the while() loop, I can't specify the right ID from the right table.
I would appreciate it if you could help me out with what I need to change, add or delete to make this work.
<?php
include 'inc/inc.php';
$artikel = mysqli_query($mysql, "SELECT a.Artikel_ID, a.Productnaam, aw.Artikel_ID, aw.Webshop_ID, aw.Prijs, w.Webshop_ID, w.Shopnaam FROM artikel a, artikel_webshop aw, webshops w WHERE a.Artikel_ID = aw.Artikel_ID AND aw.Webshop_ID = w.Webshop_ID GROUP BY aw.Webshop_ID, aw.Artikel_ID");
echo '<table id="specialtable"><tr style="background-color:#F8F8F8;"><td>Productnaam</td><td>Webshop</td><td>Prijs</td><td>Wijzigen</td></tr>';
$i = 0;
$j = 1;
while($artikelR = mysqli_fetch_assoc($artikel)) {
$artikel_id = $artikelR['Artikel_ID'];
$webshop_id = $artikelR['Webshop_ID'];
echo '<form method="post">';
if($i == 0){
echo '<tr style="background-color:#DDD;">';
$i = $i + 1;
}else{
echo '<tr style="background-color:#F8F8F8;">';
$i = $i - 1;
}
echo '<td>' . $artikelR['Productnaam']. '</td><td>' . $artikelR['Shopnaam'] . '</td><td>€ <input type="text" name="' . $j . '" value="' . $artikelR['Prijs']. '"></td>';
echo '<td><input type="submit" name="' . $j . '" value="Wijzigen"></td></tr></form>';
$jNew = $_POST['' . $j . ''];
$j++;
$test = $_POST['' . $j . ''];
if(isset($test)) {
$sql = mysqli_query($mysql, "
UPDATE artikel_webshop
SET Prijs = '" . $jNew . "'
WHERE Artikel_ID = '$artikel_id'
AND Webshop_ID = '$webshop_id'");
echo 'U heeft succesvol de prijs van het artikel ' . $artikelR['Productnaam'] . ' van de webshop ' . $artikelR['Shopnaam'] . ' gewijzigd.<br><br>';
$url = 'prijsWij.php';
echo '<meta http-equiv="refresh" content="4;URL=' . $url . '">';
}
}
echo '</table></form>';
?>
Edit
I finally got it to work. I'm pretty bad at explaining, so I'll just add the new code:
<?php
include 'inc/inc.php';
$artikel = mysqli_query($mysql, "
SELECT a.Artikel_ID, a.Productnaam, aw.Artikel_ID as awa_id, aw.Webshop_ID as aww_id, aw.Prijs, w.Webshop_ID, w.Shopnaam
FROM artikel a, artikel_webshop aw, webshops w
WHERE a.Artikel_ID = aw.Artikel_ID
AND aw.Webshop_ID = w.Webshop_ID");
echo '<table id="specialtable"><tr style="background-color:#F8F8F8;"><td>Productnaam</td><td>Webshop</td><td>Prijs</td><td>Wijzigen</td></tr>';
$i = 0;
$j = 1;
while($artikelR = mysqli_fetch_assoc($artikel)){
$artikel_id = $artikelR['awa_id'];
$webshop_id = $artikelR['aww_id'];
echo '<form method="post">';
if($i == 0){
echo '<tr style="background-color:#DDD;">';
$i = $i + 1;
}else{
echo '<tr style="background-color:#F8F8F8;">';
$i = $i - 1;
}
echo '<td>' . $artikelR['Productnaam']. '</td><td>' . $artikelR['Shopnaam'] . '</td>';
echo '<td>€ <input type="text" name="prijsTest" value="' . $artikelR['Prijs']. '"></td>';
echo '<td><input type="submit" name="' . $j . '" value="Wijzigen"></td></tr></form>';
$kNew = $_POST['prijsTest'];
$test = $_POST['' . $j . ''];
$j = $j + 1;
if(isset($test)){
$sql = mysqli_query($mysql, "
UPDATE artikel_webshop
SET Prijs = " . $kNew . "
WHERE Artikel_ID = '$artikel_id'
AND Webshop_ID = '$webshop_id'");
echo 'U heeft succesvol de prijs van het artikel ' . $artikelR['Productnaam'] . ' van de webshop ' . $artikelR['Shopnaam'] . ' gewijzigd.<br><br>';
$url = 'prijsWij.php';
echo '<meta http-equiv="refresh" content="4;URL=' . $url . '">';
}
}
echo '</table></form>';
?>
SELECT a.Artikel_ID as a_id, a.Productnaam, aw.Artikel_ID as aw_id ...
In order to know which article was updated, you need to keep track of it in your form so that when the form gets submitted, you will be able to update the correct article.
It seems like you have one form per article. In this case, it's easy. When you generate your form, add a hidden input containing the article ID:
<input type="hidden" name="article_id" value="<?php echo $articleId; ?>"/>
When the form will be submitted, the article ID will be posted along with the new price. You can retrieve it through $_POST['article_id']. Then, you can use this variable in your MySQL query to update the right article!

PHP Leaderboard add (t) for ties

I have a php leaderboard and it works great, and works well with ties. Currently it will number users from 1st to last place (whichever # that is), and if there are ties, it lists them all out with the same number.
For example:
userC 2. userG 3. userA 3. userT 3. userJ 4. userW 5. userP
What I would like is for when there are ties, for the leaderboard to display a "(t)" next to the number, like so: (t) 3. userT
Here is my code, any help is appreciated:
<table cellpadding="4" cellspacing="0" class="table1" width="100%"><caption>
<h2>Leaderboard</h2>
</caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$i = 1;
$tmpScore = 0;
//show place #
foreach($playerTotals as $playerID => $stats) {
if ($tmpScore < $stats[score]) $tmpScore = $stats[score];
//if next lowest score is reached, increase counter
if ($stats[score] < $tmpScore ) $i++;
$pickRatio = $stats[score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($stats[score] / $possibleScoreTotal) * 100), 2) . '%';
//display users/stats
$rowclass = ((($i - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $i . '</b>. ' . $stats[userName] . '</td><td align="center">' . $stats[wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$tmpScore = $stats[score];
}
}
echo ' </div>' . "\n";
?>
</table>
Try this code... hope it will resolve your issue
<table cellpadding="4" cellspacing="0" class="table1" width="100%">
<caption><h2>Leaderboard</h2></caption>
<tr><th align="left">Player</th><th align="left">Wins</th><th>Pick Ratio</th></tr>
<?php
if (isset($playerTotals)) {
$playerTotals = sort2d($playerTotals, 'score', 'desc');
$j = 1;
$tmpScore = 0;
//show place #
$tieflag=false;
for($i=0; $i<=count($playerTotals)-1; $i++) {
if(($i<count($playerTotals) && $playerTotals[$i][score]==$playerTotals[$i+1][score]) || ($i>0 && $playerTotals[$i][score]==$playerTotals[$i-1][score])) $tieflag=true;
$pickRatio = $$playerTotals[$i][score] . '/' . $possibleScoreTotal;
$pickPercentage = number_format((($playerTotals[$i][score] / $possibleScoreTotal) * 100), 2) . '%';
$rowclass = ((($j - 1) % 2 == 0) ? ' class="altrow"' : '');
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . ($tieflag?'(t)'.$j:$j) . '</b>. ' . $playerTotals[$i][userName] . '</td><td align="center">' . $playerTotals[$i][wins] . '</td><td align="center">' . $pickRatio . ' (' . $pickPercentage . ')</td></tr>';
$j++;
}
}
echo '</div>'. "\n";
?>
</table>
I'd create a new variable $placeholder. So:
if ( $i != 0 ) {
if ($tmpScore < $stats[score]) {
$tmpScore = $stats[score];
}
if ( $tmpScore == $stats[score] ) {
$placeholder = $i.'(t)';
} else if ($stats[score] < $tmpScore )
$placeholder = $++i;
}
} else {
$placeholder = $++i;
$firstScore = $stats[score];
$tmpScore = $stats[score];
}
Then instead of printing $i print $placeholder
so for the first time through you could do this in the echo:
//It makes more sense if you read it from bottom to top but I put it this way
//so you will not have to keep running through every condition when you will
//only evaluate the first condition most often
if ( $i != 0 && $i != 1 ) {
echo ;//Your normal print
} else if ( $i = 1 && $tmpScore != $firstScore ) {
echo '<b>'; //and the rest of the first line plus second line NOT a tie
} else if ( $i = 1 ) {
echo ' (t)'; //Plus the rest of your first line plus second line TIE
} else {
//This is your first time through the loop and you don't know if it's a tie yet so just
//Print placeholder and then wait to figure out the rest
echo ' <tr' . $rowclass . '><td style="height: 25px;"><b>' . $placeholder;
}

directory error in dynamic php background

I am trying to load a seperate image for each div by getting a directory from a database and inline styling
<div class="query">
<?php
if ($type == "category") {
$query = "SELECT * FROM shopItems WHERE category = '" . $_GET['query'] ."'";
$result = mysqli_query($con, $query);
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$i = $i + 1;
$url = '../img/'.$row['imgSRC'];
if ($i % 2 != 0) {
if ($i != 1) {
echo '</div>';
}
echo '<div class="queryRow"><div class="item" style"background:url(' . $url . ') no-repeat; background-size:contain;">' . $row['productName'] . '</div>';
} else {
echo '<div class="item" style"background:url(' . $url . ') no-repeat; background-size:contain;">' . $row['productName'] . '</div>';
}
}
echo "</div>";
?>
</div>
My problem is that when ever the page is loaded the slashes ("/") in the $url variable are replaced with spaces so the browser thinks an invalid url has been giver, how can i fix this?
Try
style = "background:url(' . $url . ') no-repeat; background-size:contain;"
instead of
style"background:url(' . $url . ') no-repeat; background-size:contain;"
echo '<div class="item" style = "background:url(' . $url . ') no-repeat; background-size:contain;">' . $row['productName'] . '</div>';

How do I create an order in which my images appear? (a MySQL+PHP question)

Right now, all my images are basically inserted onto my page at the same time (or so it appears). How can I create an order, so my images appear one being one left, left to right, top to bottom?
I'm using MySQL to store the image name by the way. So maybe I should create an order by ascending ID for which the image name is processed onto my php? I don't know, any recommendations would be appreciated.
This is a small bit of the code to illustrate what I mean. It's the image code being looped:
echo '<img src="https://s3.amazonaws.com/pictures/' . $objResult["Image"] . '.png" />
EDIT:
Here's the code for more context:
<html>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("dfvdfv");
$strSQL = "SELECT * FROM images";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by ImagesID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '
<td><img src="https://s3.amazonaws.com/images/' . $objResult["Image"] . '" />' .
$objResult["ImagesName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br />
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
<?php
mysql_close($objConnect);
?>
</body>
</html>
Assuming your iterating through a single loop to write your html and therefor the images it could be easily done by setting the css float attribute to left, put the images in a div container with a size of your choice, so the images row will break if they reach the right border. This will lead to building up the images from left to right.
A code example with your snippet embedded:
// open container
echo '<div style="width:\'500px\'">';
foreach ($results as $key => $objResult) {
echo '<img style="float:left;" src="https://s3.amazonaws.com/pictures/' . $objResult["Picture"] . '.png" />';
}
// close container
echo '</div>';
I suggest using stylesheet instead of setting the style attribute directly but for simplicity of the example it's just this way.
example for second question in comments
if ($objResult["description"]) {
$imageTitle = $objResult["description"];
} else {
$imageTitle = $objResult["number"];
}
echo
'<td>'.
'<img src="https://s3.amazonaws.com/images/' . $objResult["Image"] . '" />' .
$imageTitle .
'</td>';
If you want to change the order in which images appear, add a sort_order column to your database and put an index on it. When you add pictures, increment the sort_order. I prefer to increment by 10 so I have room to move images in-between others.
When you select from the database make sure you ORDER BY sort_order.

Categories