简体   繁体   中英

Use SQL Result to Query second time and grab more results via php

I am grabbing a list of school names from a database. When the user clicks on the school name, i want the code to fetch 2-3 other attributes related to the school name that the user has clicked on.

My code for the single school name list:

$query = mysql_query("Select schoolname, product, username, password from credentials c
join products p on p.productid = c.productid
join schools s on s.schoolid = c.schoolid
join icons i on i.productid = p.productid
order by s.schoolname");

echo '<ul>';
while($row = mysql_fetch_array($query))
{                   
echo "<li> <a href='#'>" . $row['schoolname'] . "</a> </li>";
}

echo '';

Current Output:

  • School A
  • School A
  • School B
  • School B
  • School B
  • School C
  • School C

Expected Output:

  1. School name displayed only once (distinct won't work because each school name has 2-3 product credentials

    • School A
    • School B
    • School C
  2. Ability for User to click on a school. then the school names underneath will move down (toggle effect) and user can see product, username and password displayed for the school clicked (for example: user clicked on School A)

    • School A
    • productname1, username, password
    • productname2, username, password

    • School B

    • School C

1) You should use GROUP BY schoolname, but note that this only would give you only one value for one unique schoolname row, and thus you might lose some other data. Also you might need multiple GROUP BY statements if you want fetch all data at once and not lose your product credentials

2) There are few ways of doing this. You can fetch all needed data at once, generate html output with school and hidden product names and toggle them via javascript.

<div class = "school-name">
    School name 1
    <div class = "product-name" style="display: none;">Product1</div>
    <div class = "product-name" style="display: none;">Product2</div>
    <div class = "product-name" style="display: none;">Product3</div>
</div>

and javascript, i'm using jquery for it

$(document).ready(function() {
    $('.school-name').on('click', function(e) {
        $(e.currentTarget).children('.product-name').show();
    }
});

This approach works fine as soon as you have small amounts of data. Otherwise, it's a better practice to use AJAX call to get children nodes of element.

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