我正在开发一个基于电子购物的大学项目,我尝试使用此代码来实现我的结果,这没有错误但是当我按下一页链接或“按钮”时它不起作用请帮助任何帮助将不胜感激
<?php
$con = mysqli_connect("localhost","root","","php184_proj_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $qry to be your query
$qry = "SELECT * FROM posts";
$result = mysqli_query($con,$qry);
$row = mysqli_num_rows($result);
//This is the number of results displayed per page
$page_rows = 5;
//This tells us the page number of our last page
$last = ceil($row/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1; //Pagination of MySQL Query Results Setting the Variables
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$j=0;
$qry = "SELECT * FROM posts $max";
$result = mysqli_query($con,$qry);
while($row = mysqli_fetch_array($result))
{
$j++;
echo "<p>";
// This shows the user what page they are on, and the total number Query and Results of pages
echo " --Page $pagenum of $last--
<p>";
// 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 " <a
href='{$_SERVER['PHP_SELF']}?pagenum=1'>
<<-First</a>
";
echo " ";
$previous = $pagenum-1;
echo " <a
href='{$_SERVER['PHP_SELF']}?
pagenum=$previous'> <-Previous</a>
";
}
//just a spacer
echo " ---- ";
//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 " <a
href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next
-></a> ";
echo " ";
echo " <a
href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last
->></a> ";
}
?>
答案 0 :(得分:3)
如果您访问此网址:http://example.com/somepage.php?key=val
,则不会在PHP中自动获取变量$key
。相反,您必须使用$_GET['key']
,它将保留该值。 (在这种情况下:'val')
因此,在代码开头的某处,添加以下内容:
if (isset($_GET['pagenum']) && $_GET['pagenum'] >= 1) {
$pagenum = (int) $_GET['pagenum'];
} else {
$pagenum = 1;
}
这不仅会创建$pagenum
变量并从URL中提供值,还会确保该值是有效数字。如果没有,或者该网址不包含pagenum
,则会将其设置为1
。
可能的情况:
pagenum
不包含整数,而是包含字符串(甚至可能是SQL injection次尝试)pagenum
是一个负数,或0 pagenum
未设置在上述所有情况下,pagenum
都设置为1
。
如果pagenum
包含一个浮点数(例如1.5.
),则该值将转换为整数。在1.5的情况下,pagenum
将变为1。
请记住,始终确保您清理用户输入。