PHP分页与WHERE子句

时间:2015-01-28 06:47:10

标签: php mysql

<html>
<body>
<center>
<div>    
<form method="post" action="admission_list_fetch5.php">
Enter Cousre Code: <input name="course_code" placeholder="course code">
<input type="submit" name="submit" value="Submit">
</form>

<div>
     <table border="2" id="enquirytable" style= "border-collapse:collapse;"">
      <thead>
        <tr>
          <th style="width:50;">SL No</th>
          <th>Student ID</th>
          <th>Enrol No</th>
          <th>Name</th>
          <th>Course</th>
          <th>Semester</th>
        </tr>
      </thead>
      <tbody>

<?php 
//error_reporting(0);
$num_rec_per_page=10;
mysql_connect('localhost','root','');
mysql_select_db('nobledatabase');
if (isset($_GET["page"])) { $page  = $_GET["page"]; } else { $page=1; }; 
$start_from = ($page-1) * $num_rec_per_page; 
$course_code=$_POST['course_code'];

$sql = "SELECT * FROM admission_list where course_code='$course_code' LIMIT $start_from, $num_rec_per_page"; 
$rs_result = mysql_query ($sql); //run the query

        $i=1;
          while( $row = mysql_fetch_assoc( $rs_result ) )
    {
        echo ("<tr><td  style='text-align:center'>$i</td>".
        "<td>{$row['student_id']}</td>".
        "<td>{$row['enrol']}</td>".
        "<td>{$row['name']}</td>".
        "<td>{$row['course']}</td>".
        "<td>{$row['sem_year']}</td></tr>\n");
        $i++;
          }
        ?>
      </tbody>
    </table>

<?php
$sql="SELECT * FROM admission_list where course_code='$course_code'";
$rs_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($rs_result);  //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
?>

</div><!--enquirytable-->

<div class="enquirypages">
<br>
<?php
echo "<a href='admission_list_fetch5.php?page=1&course_code=$course_code'>".'<<'."</a> "; // Goto 1st page  

for ($i=1; $i<=$total_pages; $i++) { 
            echo "<a href='admission_list_fetch5.php?page=".$i."&course_code=$course_code'> ".$i." "; 
}; 
echo "<a href='admission_list_fetch5.php?page=$total_pages&course_code=$course_code'>".'>>'."</a> "; // Goto last page

?>
</div>

</div>
</center>
</body>
</html>

即使我将参数传递给所有页面,我也会收到相同的错误消息:

Notice: Undefined index: course_code in C:\wamp\www\admission_list_fetch5.php on line 33 

1 个答案:

答案 0 :(得分:3)

当我查看逻辑时,似乎提供course_code变量的唯一值来自$_POST['course_code']。这意味着您每次都必须从表单post提交以填充此变量。

假设第二个代码和平是admission_list_fetch5.php。 每当发生分页时,点击<a href链接,在任何时候都不会传递查询字符串,而是使用$_GET['course_code']分配course_code。因此,course_code查询字符串将始终为空。

我会根据假设admission_list_fetch5.php

建议以下内容
if(isset($_POST['course_code']))
{
   $course_code = $_POST['course_code'];
}

if(isset($_GET['course_code']))
{
   $course_code = $_GET['course_code'];
}

不是很优雅但是有目的。当您发布到此页面时,应该没有查询字符串,因此代码将默认为$_POST['course_code']。如果设置了查询字符串,那么它将使用$_GET['course_code']覆盖。