0

下面是我的代码的一部分。我创建了一个文本框,当用户在文本框中输入单词/短语时,它会在数据库中搜索关键字。此代码还包含分页代码。我在这段代码中面临的问题是它第一次显示页码但在第一次它不显示所需的结果。当我从一页移动到另一页时,它会丢失变量“$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 &nbsp; 
            <br> Region: $region </td> </tr>";
        }
    }   
}
echo "</tbody>";
4

2 回答 2

0

请不要在新代码中使用 mysql_* 函数。它们不再被维护并被正式弃用。看到红框了吗?改为了解准备好的语句,并使用PDOMySQLi -本文将帮助您决定使用哪个。如果您选择PDO这里有一个很好的教程。

于 2013-03-04T02:39:42.580 回答
0

您需要将搜索条件添加到分页链接 ( k=$k1),因为它目前仅在您提交表单时设置。尝试类似的东西 -

if($pages >= 1 && $page <= $pages){ 
   for($x = 1; $x <= $pages; $x++) {
        echo '<a href="?k='.$k1.'&page='.$x.'">'.$x.'</a> ';
   }

注意-您当前在$k1=>中使用未经处理的用户输入$each

于 2013-03-04T02:58:02.947 回答