我正在尝试创建一段代码,将我的查询结果限制为每页2个结果,其余结果可以通过点击页码来查看,就像谷歌搜索到的那样如果我想要更多的结果,我只需要转到第2页。如何使用PhP完成。没有javascript。
<!DOCTYPE html>
<html>
<head>
<title>Database</title>
<link href="style.css" rel="stylesheet" type="text/css"> <!-- This is linking style sheet (css)into this HTML page-->
<link href='https://fonts.googleapis.com/css?family=PT+Serif:400italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="navigation">
<form action="index.php" method="get">
<input type="submit" name="mainpage" value="Main Page" class="submitbut" id="but1" />
</form>
</div>
<form action="index.php" method="post">
<input type="text" name="search" id="searching" />
<input type="submit" name="data_submit" value="Search" id="scan" />
</form>
<?php
if( isset( $_GET['mainpage'] ) ) exit( header( "Location: mainpage.php" ) );
if ( isset( $_POST["data_submit"] ) ){
$search_term = ( $_POST['search']);
if($search_term == ""){
echo "You need to enter a value";
}else{
$conn = new PDO( 'mysql:host=localhost;dbname=u1358595', 'root' );
/*
replace root with this
'u1358595'
'26nov94'
*/
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN `hotel` h ON b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term OR g.`first_name` LIKE :search_term;");
$stmt->bindValue(':search_term', '%' . $search_term . '%');
$stmt->execute();
$count=($stmt->rowCount());
echo "There are ".$count." results that match your search";
echo "
<table>
<tr>
<th>Guests Matched</th>
</tr>";
while($hotel = $stmt->fetch()) {
echo "
<tr>
<td><a href='details.php?name=".$hotel['last_name']."'>".$hotel['first_name']." ".$hotel['last_name']."</a></td>
</tr>";
}
echo "</table>";
$conn = NULL;
}
}
?>
</body>
</html>
答案 0 :(得分:0)
在SQL中,使用LIMIT
子句:
直接来自文档:
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
https://dev.mysql.com/doc/refman/5.5/en/select.html
所以在你的例子中,你会做这样的事情:
$results_per_page = 24;
$current_page = isset($_GET['page']) ? (int) $_GET['page'] : 0;
$stmt = $conn->prepare("SELECT * FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN `hotel` h ON b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term OR g.`first_name` LIKE :search_term
LIMIT :offset, :row_count");
$stmt->bindValue(':search_term', '%' . $search_term . '%');
$stmt->bindValue(':offset', ($current_page * $results_per_page));
$stmt->bindValue(':row_count', $results_per_page);
$stmt->execute();
使用$_GET
变量更改页面:
http://localhost/?page=2
关于总结果的计数,您必须运行另一个查询来选择该搜索查询的所有结果,但只返回COUNT(*)
输出:
SELECT COUNT(*) FROM `guest` g
INNER JOIN `booking` b ON g.`guest_id`=b.`guest_id`
INNER JOIN `hotel` h ON b.`hotel_id`=h.`hotel_id`
WHERE g.`last_name` LIKE :search_term OR g.`first_name` LIKE :search_term