简体   繁体   中英

Join results from multiple MySQL tables and output with PHP

Using PHP, I'm trying to populate an HTML list with data from two different tables in a MySQL database. The structure for each table is as follows:

Table: "students"
+------------+------------+-----------+---------------+-------+
| student_id | first_name | last_name | city          | state |
+------------+------------+-----------+---------------+-------+
| 1          | Tobias     | Funke     | Newport Beach | CA    |
+------------+------------+-----------+---------------+-------+
| 2          | Bob        | Loblaw    | Laguna Beach  | CA    |
+------------+------------+-----------+---------------+-------+
| 3          | Ann        | Veal      | Bland         | CA    |
+------------+------------+-----------+---------------+-------+


Table: "students_current"
+------------+------------+---------------+
| student_id | school_id  | current_class |
+------------+------------+---------------+
| 1          | umass      | Sr            |
+------------+------------+---------------+
| 2          | ucla       | Jr            |
+------------+------------+---------------+
| 3          | ucla       | Fr            |
+------------+------------+---------------+

I'd like to populate the list with only with records that match a specific school_id .

For example, if I want the list only to contain students whose school_id is "ucla", the resulting HTML would be as follows:

<li>
    <span class="first_name">Bob</span>
    <span class="last_name">Loblaw</span>
    <span class="city">Laguna Beach</span>
    <span class="state">CA</span>
    <span class="current_class">Jr</span>
</li>

 <li>
    <span class="first_name">Ann</span>
    <span class="last_name">Veal</span>
    <span class="city">Bland</span>
    <span class="state">CA</span>
    <span class="current_class">Fr</span>
</li>

Each <li> item would be tied to a specific student_id value from the database. How do I write the PHP that will select/join the appropriate records from the database?

Using a LEFT JOIN :

SELECT *
FROM `students` s
    LEFT JOIN `students_current` sc ON s.`student_id` = sc.`student_id`
WHERE `school_id` = 'ucla'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM