如何仅返回满足用户搜索条件的选定行

时间:2016-04-23 23:02:44

标签: php html mysql

我有一个网页(我是初学者php,只有1.5个月的书籍示例),允许用户输入gpa,然后搜索符合最低输入条件的学生。单击搜索按钮时,它会调用php文件中的函数来查询数据库。我的代码几乎正常工作。问题是它返回所有学生,我只想返回符合最小gpa的行。试图使用HAVING子句和其他但仍然没有返回我想要的。谢谢!

链接到sql小提琴:http://www.sqlfiddle.com/#!2/be9da

HTML:

<script type="text/javascript">
function queryStudent() {
    var ajaxRequest = new XMLHttpRequest;
    ajaxRequest.onreadystatechange = function() {
        if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
            document.getElementById("ajax_output").innerHTML = ajaxRequest.responseText;
        }
    };
    ajaxRequest.open("GET", "gpa_search.php", true);
    ajaxRequest.send(null);
}
</script>   
<form name="student">
<label>Minimum GPA: </label>
<input type="text" id="GPA" name="gpa"><br><br>

<input type="button"  onclick="queryStudent();" value="Search" id="button">
</form><br>
<!--output section after search-->
<section id="ajax_output">

</section><br><br>

<p>Students with higher than minimum GPA will be displayed here.</p><br>

<a href="search_split.htm">Search & Split</a>

php:

<?php
//get user input from text box on index.htm
$GPA = filter_input(INPUT_GET, 'GPA');
//Code for query
$query = 'SELECT *
          FROM student
          ORDER BY studentID';
$statement = $db->prepare($query);
$statement->bindValue(':GPA', "%".$GPA."%", PDO::PARAM_STR); 
$statement->execute();
$students = $statement->fetchAll();
?>
<!--table to hold output-->
<table>
<tr>
<th>Student ID</th>
<th>Name</th>
<th>Email</th>
<th>GPA</th>
</tr>

<?php foreach ($students as $student) : ?> 
<tr>
    <td><?php echo $student['studentID']; ?></td>
    <td><?php echo $student['name']; ?></td>
    <td><?php echo $student['email']; ?></td>
    <td><?php echo $student['GPA']; ?></td>
</tr>
<?php endforeach; ?>

</table>
<body>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

在您的代码上使用以下内容:

$GPA

这将搜索GPA大于且等于WHERE GPA = :GPA的学生。如果您想要检索仅具有该GPA的学生,请更改{{#each Children}} {{#if Settings.IsChildTypeOne}} {{../type}} {{/if}} {{/each}}

答案 1 :(得分:0)

检查您的SQL查询,错误最有可能来自那里。您的select语句没有where子句。它应该类似于select * from students where GPA = :GPA Order by studentid