我正在使用以下代码将分页应用于数据库中的大表。它工作正常,但我无法弄清楚如何在WHERE Week="?"
中使用SELECT Query
变量应用$start $limit
(表格中的52周)。这样,当我按下PREVIOUS或NEXT按钮时,它将转到该周的上一行或下周行。
<div id="content">
<?php
include("dbconfig.php");
$start=0;
$limit=10;
if(isset($_GET['id']))
{
$id=$_GET['id'];
$start=($id-1)*$limit;
}
else{
$id=1;
}
//Fetch from database first 10 items which is its limit. For that when
page open you can see first 10 items.
$query=mysqli_query($dbconfig,"select * from user LIMIT $start, $limit");
?>
<ul>
<?php
//print 10 items
while($result=mysqli_fetch_array($query))
{
echo "<li>".$result['username']."</li>";
}
?>
</ul>
<?php
//fetch all the data from database.
$rows=mysqli_num_rows(mysqli_query($dbconfig,"select * from user"));
//calculate total page number for the given table in the database
$total=ceil($rows/$limit);
if($id>1)
{
//Go to previous page to show previous 10 items. If its in page 1 then it is inactive
echo "<a href='?id=".($id-1)."' class='button'>PREVIOUS</a>";
}
if($id!=$total)
{
////Go to previous page to show next 10 items.
echo "<a href='?id=".($id+1)."' class='button'>NEXT</a>";
}
?>
<ul class='page'>
<?php
//show all the page link with page number. When click on these numbers go to particular page.
for($i=1;$i<=$total;$i++)
{
if($i==$id) { echo "<li class='current'>".$i."</li>"; }
else { echo "<li><a href='?id=".$i."'>".$i."</a></li>"; }
}
?>
</ul>
</div>
答案 0 :(得分:1)
您可能正在寻找几周的选择框,然后在where子句中使用该值。
<select name="weeks">
<?php
for( $i = 1; $i <= 52; $i++ ):
echo '<option name="week" value="'.$i.'"></option>';
endfor;
?>
</select>
查询:
$mysqli = dbConnect();
$stmt = $mysqli->prepare( $sql );
if( !empty( $_POST['weeks'] ) ):
$week = $_POST['week'];
// Validate the data
$week = trim( $week );
$week = htmlspecialchars( $week );
if( !ctype_digit( $week ) ):
echo 'Week is not a valid input';
else:
// Prepared statement
$sql = "SELECT * FROM user WHERE week = ? LIMIT ?, ?";
$stmt->bind_param("iii", $week, $start, $limit);
endif;
else:
$sql = "SELECT * FROM user LIMIT ?, ?";
$stmt->bind_param("ii", $start, $limit);
endif;
$stmt->execute();
$stmt->bind_result(yourparamshere);
$stmt->close();
$mysqli->close();
注意:
请查看http://php.net/manual/en/pdo.prepared-statements.php
预备语句和存储过程更加安全,可以让您成为更好的程序员。