[英]Result after adding pagination code is getting messed up in PHP
以下是我的代码的一部分。 我创建了一个文本框,当用户在文本框中输入单词/短语时,它将在数据库中搜索关键字。 此代码还包含分页代码。 我在这段代码中面临的问题是,它第一次显示页码,但是在第一次显示时却没有显示所需的结果。 当我从一页移到另一页时,它将丢失变量“ $ each”中的值,并显示数据库中的所有结果。 而此代码应仅显示满足查询条件的部分数据
<input type="text" name="k"
value="<?php if(isset($_GET['k'])){echo htmlentities($_GET['k']);} ?>" style="border: 1px, thin; width:92%; "/>
<input type="image" style="margin-bottom: 0; margin-top: 2px;" src="search.png" value="submit" />
</div>
</fieldset>
</form>
</div>
<table cellpadding="0" cellspacing="0" border="1">
<tbody>
<?php
$connection = mysql_connect('', '', '');
if(!$connection)
echo "No database connected";
$dbase = mysql_select_db("", $connection);
if(!$dbase)
echo "No datatable connected";
if(isset($_GET['k'])){
$k1 = $_GET['k'];
} else {
$k1 = '';
}
echo $k1;
$term = explode(" ", $k1);
$query = "SELECT * FROM kcpdatabase ";
foreach ($term as $each) {
echo $each;
$i++;
if($i==1) {
$query .= "WHERE keywords LIKE '%$each%' ";
} else {
$query .= "OR WHERE keywords LIKE '%$each%' ";
}
}
echo $query;
$per_pages=3;
$page_query = mysql_query("SELECT COUNT('title') FROM kcpdatabase");
$pages = ceil(mysql_result($page_query, 0)/$per_pages) or die($page_query."<br/><br/>".mysql_error()); //Calculating the number of pages and round it to higher side
$page = (isset($_GET['page'])) ? (int) ($_GET['page']) : 1; //Checking wheather value of page is set or not.
//If not then assign it as a default value of 1.
$start = ($page - 1) * $per_pages; // Point to the record zero always to start displaying the data
$query .= "LIMIT $start, $per_pages";
$ourquery1 = mysql_query ($query);
if(!$ourquery1)
echo "No query found";
$row1 = mysql_num_rows ($ourquery1);
if($pages >= 1 && $page <= $pages){
for($x = 1; $x <= $pages; $x++) {
echo '<a href="?page='.$x.'">'.$x.'</a> ';
}
if ($row1 > 0) {
while($result = mysql_fetch_assoc($ourquery1)) {
echo "<tr>";
echo "<td>";
$title = $result['title'];
$link = $result['link'];
$region = $result['region'];
$sector = $result['sector'];
$theme = $result['theme'];
echo "<td> <a href=$link><h3>$title<h3></a>";
echo "<h4>Sector: $sector Theme: $theme
<br> Region: $region </td> </tr>";
}
}
}
echo "</tbody>";
请不要在新代码中使用mysql_ *函数 。 它们已不再维护,已正式弃用。 看到红色框了吗? 相反,要了解准备好的语句 ,并使用PDO或MySQLi- 本文将帮助您确定哪一个。 如果选择PDO , 这是一个很好的教程。
您需要将搜索条件添加到分页链接( k=$k1
),因为当前仅在提交表单时设置该条件。 尝试类似-
if($pages >= 1 && $page <= $pages){
for($x = 1; $x <= $pages; $x++) {
echo '<a href="?k='.$k1.'&page='.$x.'">'.$x.'</a> ';
}
注意-您当前在$k1
=> $each
使用未经过滤的用户输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.