搜索关系数据库中的记录

时间:2015-03-13 16:55:15

标签: php mysqli

情景:

我正在开发一个PHP / MySQLi应用程序,我有两个表attendancestudents

students包含字段:student_id,fullname,phone,email,gender,department和level。

attendance表包含字段:attendance_id,student_id,department_id,level_id。

我能够根据他们的部门和级别取得所有记录在考勤表中的学生。

问题:

我们假设我能够取出所有记录在考勤表中并且在200L(带有level_id,2)计算机科学(有department_id,4)部门的学生,如果在场的学生名单很多,它是分页的,我想在参考学生表的桌子上搜索特定学生的全名。

SQL查询将如何?我尝试了以下不起作用的查询。

$search_query = mysqli_query($db_connect, "SELECT *FROM attendance WHERE student_id=\"SELECT student_id FROM students WHERE fullname LIKE '%$student_fullname%'\";

请帮忙。

2 个答案:

答案 0 :(得分:1)

尝试此查询:

SELECT attendance.*
FROM `students`
INNER JOIN `attendance` 
  ON `attendance`.`student_id` = `students`.`student_id`
WHERE `students`.`fullname` LIKE `%$student_fullname%`

我知道这可能首先看起来是前瞻性的,但我更喜欢构造SQL以在WHERE子句中显示强选择器(LIKE过滤器)。如果你不喜欢这样,你可以得到相同的结果:

SELECT attendance.*
FROM `attendance`
INNER JOIN `students`
  ON `students`.`student_id` = `attendance`.`student_id`
    AND `students`.`fullname` LIKE `%$student_fullname%`

请注意,第二个版本没有WHERE子句 - 总是在join的ON子句中的连接的RHS上放置过滤器,因为否则外连接将无法正常运行。

答案 1 :(得分:0)

您正在寻找的SQL查询是:

select * from attendance join students on attendance.student_id = students.student_id where students.fullname like '%NAME%'

所以在PHP中你需要像:

$query_string = "select * from attendance join students on attendance.student_id = students.student_id where students.fullname like '%$student_fullname%'";
$search_query = mysqli_query($db_connect, $query_string);

我建议你看看预备语句,以防止SQL注入:http://php.net/manual/en/mysqli.prepare.php

/* create a prepared statement */
$query_string = "select * from attendance join students on attendance.student_id = students.student_id where students.fullname like ?";
if ($stmt = $mysqli->prepare($query_string)) {
    $stmt->bind_param("s", $student_fullname);
    $stmt->execute();
    $result = $stmt->get_result();
    while ($myrow = $result->fetch_assoc()) {
        // use your $myrow array as you would with any other fetch
        printf("%s found in attendance record ID: %s\n", $student_fullname, $myrow['attendance_id']);
    }
    $stmt->close();
}