PHP pagination add ID - php

I have a kind of problem, with following php code:
$host="localhost";
$user_name="";
$pwd="";
$database_name="";
$conexiune = mysql_connect($host,$user_name,$pwd) or die("Nu ma pot conecta la MySQL!");
mysql_select_db($database_name, $conexiune) or die("Nu gasesc baza de date");
if (isset($_GET["page"])) {
$page = $_GET["page"];
} else {
$page=1;
};
$start_from = ($page-1) * 1;
$sql = "SELECT * FROM citate ORDER BY id DESC LIMIT $start_from, 1";
$rs_result = mysql_query ($sql,$conexiune);
while ($row = mysql_fetch_assoc($rs_result))
echo "<img src='" . $row['poza'] . "' />
<br />
" . $row['titlu'] . "
<br />
" . $row['descriere'] . "
<br />
" . $row['data'] . "
";
$sql = "SELECT COUNT(id) FROM citate";
$rs_result = mysql_query($sql,$conexiune);
$row = mysql_fetch_row($rs_result);
$total_records = $row[0];
$total_pages = ceil($total_records / 1);
$pagelink ='<< ';
$pagelink_2='>> ';
if($page>1)
echo $pagelink;
if($page<2)
echo "";
for ($i=1; $i<=$total_pages; $i++) {
if ($i != $page)
echo "<a href='lista.php?page=".$i."'>".$i."</a> "; // xxxx = your page url address
if ($i==$page)
echo " <strong>". $i . "</strong> "; // defining class in the style sheet you can add colour or border to the displayed number
};
if($page<$total_pages)
echo $pagelink_2;
that code offer me pagination (u allready know that) , and the url bar adress look's like following:
http://www.site.ro/folder/lista.php?page=PAGE-NUMBER
i want to look like following:
http://www.site.ro/folder/lista.php?citat=SOME-NUMBERS&page=PAGE-NUMBER
my database table its populated like that:
--------------------------------------------------------------
| id | poza | titlu | descriere | citat | data | accesari |
--------------------------------------------------------------
i want to extract data from "citat" column , so link from url bar will look like:
http://www.site.ro/folder/lista.php?citat=EXTRACTED-FROM-CITAT&page=PAGE-NUMBER
every time when i press on next page buton, will look like:
http://www.site.ro/folder/lista.php?citat=2748925&page=1
http://www.site.ro/folder/lista.php?citat=2840194&page=2
etcetera..
how can i modify that code?
Thank in advance !

I am ignoring all your security issues.
This will work as long you display only one item per page:
$last_citat = 0;
while ($row = mysql_fetch_assoc($rs_result)) {
echo "<img src='" . $row['poza'] . "' /><br />" . $row['titlu'] . "<br />" . $row['descriere'] . " <br />" . $row['data'] . "";
$last_citat = $row['citat'];
}
and later:
$pagelink ='<< ';
$pagelink_2='>> ';
if($page>1) { echo $pagelink; }
if($page<2) { echo ""; }
for ($i=1; $i<=$total_pages; $i++) {
if ($i != $page) {
echo "<a href='lista.php?citat=".$last_citat."&page=".$i."'>".$i."</a> ";
}
if ($i==$page) {
echo " <strong>". $i . "</strong> ";
}
}

Do you want to filter database results by 'citat' value?
If so, then you have to build links with get parameter 'citat' in them, like:
<<
and later take GET['citat'] and add it in the sql query where part so that only results with certain citat value would be returned, like:
$sql = "SELECT * FROM citate WHERE citat = '".GET['citat']."' ORDER BY id DESC LIMIT $start_from, 1";
NOTE: This is not real example and it is WRONG TO USE LIKE WRITTEN: you must escape GET['citat'] because otherwise your database will be hacked very easily and very soon!

Get value of citat from while loop:
$citat = $row['citat'];
Then you can use $citat wherever and however you want, and to check the citat parameter in url you can do it by:
if (isset($_GET['citat'])) {
//it's there do something
} else {
//it's absent
}

Related

php clicking on users name to display profile

So i have this code to display all the users in my database and to access them. That works fine but is there any way to get where it says click here just to display a variable in this case the leader name(aka user name)?
<?php
require_once "config.php";
$sql = "SELECT id , leader_name, nation_name, power FROM nation_info";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$nationList = [];
$userid = $row['id'];
echo ' click here '; // the click here on this line
// echo '<a class="viewProfile" href="viewnation.php?id=' . $userid . '"><button>View Profile</button></a>'; old method of viewing profile
echo " Nation Name: " . $row["nation_name"]. " Leader Name " . $row["leader_name"]. " Power " . $row["power"];
echo "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>
Are you talking about this? Just printing the name in place of click here?
<?php
require_once "config.php";
$sql = "SELECT id , leader_name, nation_name, power FROM nation_info";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$nationList = [];
$userid = $row['id'];
echo ' ' . $row["leader_name"] . ' '; // the click here on this line
// echo '<a class="viewProfile" href="viewnation.php?id=' . $userid . '"><button>View Profile</button></a>'; old method of viewing profile
echo " Nation Name: " . $row["nation_name"]. " Leader Name " . $row["leader_name"]. " Power " . $row["power"];
echo "<br>";
}
} else {
echo "0 results";
}
$link->close();
?>

"Next" button doesn't refresh page with next 25 results

I have the code below and am trying to get the next 25 results from my sql table to appear on page. However, whenever I click the next button, no information is displayed. I have my offset = ($page - 1) * $items_per_page......I'm struggling to figure this out as it seems so simple compared the other code I've written, but is proving to be very elusive to me....any assistance would be greatly appreciated. My primary issue is that the next link does not provide the next 25 results and I'm unable to determine why and how to correct.
echo "<h3 style='text-align:center;'>Welcome to the Exchange Portal, " . $row['name'] . "! </h3>";
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if(false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page-1)*$items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
//Table for displaying query results
echo "<table class='verify'>";
echo "<tr >";
echo "<td><h3>Name</h3></td><td> </td><td><h3>E-mail</h3></td><td><h3>Phone</h3></td>";
echo "</tr>";
for($i = 1; $i<= $page_count; $i++) {
if ($result_query->num_rows > 0) {
// output data of each row
while($row3 = mysqli_fetch_array($result_query)) {
echo "<tr>";
echo "<td class='dltd2 dlcl'>" . $row3["title"] . "</td><td>" . $row3["title2"] . "</td><td><a href='mailto:" . $row3['email'] . "'>" . $row3["email"] . "</a> </td><td>" . $row3["phone"] . " </td>";
echo "</tr>";
}
} else {
echo "0 results";
}
}
echo "<tr></tr>";
$next_page = $page + 1;
$last_page = $page - 1;
if($paging_info['curr_page'] <= 1) {
echo "<tr>";
echo "<td></td><td colspan='2'><a class='loadlink' href='" . $_PHP_SELF . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] < $page_count) {
echo "<tr>";
echo "<td></td><td><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td><a href='" . $_PHP_SELF . "?page=" . $next_page . "'>Next 25</a></td><td></td>";
echo "</tr>";
} elseif ($paging_info['curr_page'] === $page_count) {
echo "<tr>";
echo "<td></td><td colspan='2'><a href='" . $_PHP_SELF . "?page=" . $last_page . "'>Prev 25</a></td><td></td>";
echo "</tr>";
}
echo "</table>";
}
}
}
Have you tried to run the rendered SQL.
Output to browser:
"SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page"
try this... and change $page for different values (2,3,...,etc)
<?php
$items_per_page = 25;
$sql_count = "SELECT pin, title, title2, email, phone FROM crown_acura";
$result_cnt = mysqli_query($conn, $sql_count);
if (false === $result_cnt) {
throw new Exception('Query failed with: ' . mysqli_error());
} else {
$row_count = mysqli_num_rows($result_cnt);
// free the result set as you don't need it anymore
//mysqli_free_result($result_cnt);
}
echo $row_count;
echo " ";
if (!isset($_GET['Page'])) {
$Page = 1;
} else {
$Page = $_GET['Page'];
}
echo $page;
echo " ";
$page_count = 0;
if (0 === $row_count) {
// maybe show some error since there is nothing in your table
} else {
// determine page_count
$page_count = (int)ceil($row_count / $items_per_page);
// double check that request page is in range
if ($page > $page_count) {
// error to user, maybe set page to 1
$page = 1;
}
}
echo " ";
echo $page_count;
echo " ";
echo $items_per_page;
$offset = ($page - 1) * $items_per_page;
//echo $paging_info;
//echo " ";
echo "<br />";
//Query for displaying results
$list_sql = "SELECT pin, title, title2, email, phone FROM crown_acura LIMIT $offset, $items_per_page";
$result_query = $conn->query($list_sql);
echo ("RESULTS: ".$result_query->num_rows());
?>

Php Mysql SELECT query 1 column equals 1 variable

I've been throw so many threads for 4+ hours here and abroad and seem to be missing a simple thing.
I'm trying to have several users upload their 'news' to MYSQL.
Yet I want to display only the 'news' with the logged in username (userpost) attached to the row.
$current is the username for who is logged in, which works.
Example A isn't filtering out rows that don't contain the $current user.
Example B isn't providing any output
So I've tried both A:
$result = mysqli_query($con,"SELECT * FROM images_tbl");
//echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
if ($row['userpost'] = '.$current.') {
$num = 0;
$num = $num + 1;
$pic.$num = $row['images_path'];
$h1 = $row['hlone'];
and B:
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE (userpost = '.$current.')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
27, images/08-10-2014-1412752801.jpg(images_path), 2014-10-08, Headline(hlone), Headline2, story, testb(userpost)
Any help would be greatly appreciated.
Add where clause to your query
//in situation A
$result = mysqli_query($con,"SELECT * FROM images_tbl where username='".$current."'");
//username is column name for user you might have to change this
while($row = mysqli_fetch_array($result)) {
echo $row['images_path'];
echo $row['hlone'];
}
In situation B try this
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE userpost = '".$current."')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
Why are you trying to filter with PHP.
If you want to filter the 'news' that have not written by current user just use MySQL Where clause:
// For Example A
$result = mysqli_query($con, "SELECT * FROM images_tbl WHERE userpost != '{$current}'");
while($row = mysqli_fetch_array($result)) {
$pic = $row['images_path'];
$h1 = $row['hlone'];
}
// For Example B
$result = mysqli_query($con,"SELECT * FROM images_tbl WHERE userpost = '{$current}')");
echo $current . "2" . $current;
while($row = mysqli_fetch_array($result)) {
echo $row['hlone'] . " " . $row['images_path'];
echo "<img src=\"" .$row['images_path']. "\">";
}
It's easy with MySQL's filtering options. You should do more research about MySQL.

Paginate query result with AJAX and PHP

I have a fully working pagination with get method. I get the results from my query and the page is changed when the variable pagination changes on URL. I recently changed the site to ajax and now I can't get the clicked page value from URL
I have a form with some inputs that I use to generate the query and a ajax structure that connects to the PHP file and put the result on a div
My php file:
//items per page
$quantidade = 30;
//actual page
$pagina = (isset($_GET['pagina'])) ? (int)$_GET['pagina'] : 1;
$inicio = ($quantidade * $pagina) - $quantidade;
$sql .= " LIMIT " . $inicio . " , " . $quantidade ;
$qr = mysql_query($sql) or die(mysql_error());
echo "<table id='tab_vendas' border='1' width='100%'>";
echo "<tr><td>Data</td><td>Loja</td><td>Total (AKZ)</td><td>Total (USD)</td><td>Multicaixa</td><td>Saidas</td><td>Visa</td></tr>";
$num_rows = mysql_num_rows($qr);
if($num_rows > 0){
while($ln = mysql_fetch_assoc($qr)){
echo "<tr><td>" . $ln['data']."</td>";
echo "<td>" . $ln['loja']."</td>";
echo "<td>" . $ln['totalkz']."</td>";
echo "<td>" . $ln['totaldollar']."</td>";
echo "<td>" . $ln['multicaixa']."</td>";
echo "<td>" . $ln['saidas']."</td>";
echo "<td>" . $ln['visa']."</td></tr>";
}
}else{
echo "Não foram encontrados registos";
}
echo"</table></div>";
//total
$sqlTotal = "SELECT id FROM vendas";
$qrTotal = mysql_query($sqlTotal) or die(mysql_error());
$numTotal = mysql_num_rows($qrTotal);
$totalPagina= ceil($numTotal/$quantidade);
$exibir = 3;
$anterior = (($pagina - 1) == 0) ? 1 : $pagina - 1;
$posterior = (($pagina+1) >= $totalPagina) ? $totalPagina : $pagina+1;
echo "<div id='paginacao'><a href='?pagina=1'>Primeira</a> | ";
echo "<< | ";
for($i = $pagina-$exibir; $i <= $pagina-1; $i++){
if($i > 0)
echo ' '.$i.' ';
}
echo '<strong>['.$pagina.']</strong>';
for($i = $pagina+1; $i < $pagina+$exibir; $i++){
if($i <= $totalPagina)
echo ' '.$i.' ';
}
echo " | >> | ";
echo " Ultima</div>";
My big question is how can I get the actual page value and how to know what button the user clicked.
I tried to change the link's to a submit button with form attribute that send the form again and run all code again but I can't figured out how to pass the clicked button value.
echo " | <input type='submit' form='filtros' name='$posterior' value='>>'>";
echo " <input type='submit' form='filtros' name='$totalPagina' value='Ultima'></div>";
You can simply modify your code to make this work as it was when the pages where links.
<a class="page" href="url.com?parameter=value&parameter2=value2">pageNumber</a>
javscript code is:
$('.a.page').on('click', function() {
var url = $(this).attr(href);
$.ajax({
type: 'GET',
url: url,
success: function(response) {
$('selector to the container you wish to put the data').html(response.data)
}
});
})
In your php yous should echo json_encode your data
echo json_encode(array('data' => $data));

pagination in php and keeping results

have tried to implement a pagination script in my php code (adopted from a sample code i found on the net)
the page returns resaults of a mysql query. the default is an empty 'keyword' which returns all data from databse.
succeeded as far as pagination works when all data is returned but when i filter results through a keyword search clicking 'next page' returns the next page in unfiltered results (ie the searched keyword is lost in the refresh)
this is the relevant code (hope it makes sense):
Blockquote
$txt1='<A HREF="/memimomedia/music/128kb/';
$txt2='" ><IMG src="/Save.png" width="24" height="24" align="middle" border="0"></A>';
$txt9a='<a href="';
$txt9b='" target="_blank">';
$txt9c='</a>';
$txt10a='<audio src="./128kb/';
$txt10d='" controls></audio>';
if(empty($_POST['searchkeywords']) && empty($_GET['searchkeywords'])) { $result = mysql_query("SELECT *
FROM ppl_tracks WHERE Mixed !='0' ORDER BY Track"); }
if(!empty($_GET['searchkeywords'])) { $Searchword=$_GET['searchkeywords']; }
if(!empty($_POST['searchkeywords'])) { $Searchword=$_POST['searchkeywords']; }
$Totalresults = mysql_query("SELECT Track FROM (ppl_tracks LEFT JOIN
TrackStyle ON ppl_tracks.RECNO = TrackStyle.TrackID LEFT JOIN
StyleTable ON TrackStyle.StyleID = StyleTable.ID) LEFT JOIN TrackMood
ON ppl_tracks.RECNO = TrackMood.TrackID LEFT JOIN MoodTable ON
TrackMood.MoodID = MoodTable.ID WHERE (MoodChoices LIKE
'%$Searchword%' OR Description LIKE '%$Searchword%' OR StyleChoices
LIKE '%$Searchword%' OR Tempo LIKE '%$Searchword%' OR Track LIKE
'%$Searchword%' ) AND Mixed =true GROUP BY Track ORDER BY Track" );
//This checks to see if there is a page number. If not, it will set it
to page 1 if(isset($_GET['pagenum'])) { $pagenum =
$_GET['pagenum']; } else { $pagenum = 1; }
//Here we count the number of results
$hits = mysql_num_rows($Totalresults);
//This is the number of results displayed per page
$page_hits = 15;
//This tells us the page number of our last page
$last = ceil($hits/$page_hits);
//this makes sure the page number isn't below one, or more than our
maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_hits .',' .$page_hits;
$result = mysql_query("SELECT * FROM (ppl_tracks LEFT JOIN TrackStyle
ON ppl_tracks.RECNO = TrackStyle.TrackID LEFT JOIN StyleTable ON
TrackStyle.StyleID = StyleTable.ID) LEFT JOIN TrackMood ON
ppl_tracks.RECNO = TrackMood.TrackID LEFT JOIN MoodTable ON
TrackMood.MoodID = MoodTable.ID WHERE (MoodChoices LIKE
'%$Searchword%' OR Description LIKE '%$Searchword%' OR StyleChoices
LIKE '%$Searchword%' OR Tempo LIKE '%$Searchword%' OR Track LIKE
'%$Searchword%' ) AND Mixed =true GROUP BY Track ORDER BY Track $max"
);
echo " Track -
Artist Description Download ";
$color="1";
while($row = mysql_fetch_array($result)) { $SelectedStyles =
array(); $Track=$row['Track']; $SelectedStylesQuery = mysql_query("
SELECT StyleChoices FROM ppl_tracks LEFT JOIN TrackStyle ON
ppl_tracks.RECNO = TrackStyle.TrackID LEFT JOIN StyleTable ON
TrackStyle.StyleID = StyleTable.ID WHERE ppl_tracks.Track='$Track'");
while($row1 = mysql_fetch_array($SelectedStylesQuery)) {
$SelectedStyles[] = $row1[StyleChoices]; } $SelectedMoods = array(); $SelectedMoodsQuery = mysql_query(" SELECT MoodChoices FROM
ppl_tracks LEFT JOIN TrackMood ON ppl_tracks.RECNO = TrackMood.TrackID
LEFT JOIN MoodTable ON TrackMood.MoodID = MoodTable.ID WHERE
ppl_tracks.Track='$Track'"); while($row2 =
mysql_fetch_array($SelectedMoodsQuery)) {
$SelectedMoods[] = $row2[MoodChoices]; } sort($SelectedMoods); sort($SelectedStyles); $stringS= implode(", ", $SelectedStyles);
$stringM= implode(", ", $SelectedMoods);
if($color==1) { echo ""; echo "" . $row['Track'] . " - " .
ucwords($row['Artist']) . ""; echo "" . $stringM .
"".$stringS.""; echo "" . $txt1.$row['FileName'].$txt2 .
""; echo "" . $txt10a.$row['FileName'].$txt10d."";
echo ""; $color="2"; }
else { echo ""; echo "" . $row['Track'] . " - " .
ucwords($row['Artist']) . ""; echo "" . $stringM .
"".$stringS.""; echo "" . $txt1.$row['FileName'].$txt2 .
""; echo "" . $txt10a.$row['FileName'].$txt10d."";
echo ""; $color="1";}
} echo "";
// This shows the user what page they are on, and the total number of
pages
echo " --Page $pagenum of $last-- "; // First we check if we
are on page one. If we are then we don't need a link to the previous
page or the first page so we do nothing. If we aren't then we generate
links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{ echo " <<-First ";
echo " - "; $previous = $pagenum-1; echo " <-Previous "; }
$counter=1; while ( $counter <= $last )
{
if ($counter==$pagenum)
{
echo " - ";
echo " $counter ";
echo " - ";
}
else
{
echo " - ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$counter'>$counter</a> ";
echo " - ";
} $counter = $counter + 1; }
//This does the same as above, only checking if we are on the last
page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else { $next = $pagenum+1; echo " Next -> "; echo " -
"; echo " Last ->>
"; } mysql_close($con); ?>
You are reloading the page every time you go onto a new page, so you need to pass the search term into the page again. The easiest way to do this is to update your link for pagination to the following:
echo " <a href='{$_SERVER['PHP_SELF']}?searchkeywords=" . $_REQUEST["searchkeywords"] . "&pagenum=$counter'>$counter</a> ";
$_REQUEST will handle both $_POST and $_GET variables, but you may want to do this in your own way. Simply put you just need to pass the searchkeywords back into your url

Categories