简体   繁体   中英

Displaying MySQL data from several tables using PHP while loops

After several weeks of research I have not been able to solve this. I've simplified my table structure and code to hopefully make this easier.

I have two MySQL tables; 'blocks' and 'files'.

The 'blocks' table has columns bwblock_id, bwblock_year and bwblock_name.

The 'files' table has columns file_id, file_name and bwblock_id.

A user creates a block first. Then they can create a file, and assign it to a block (bwblock_id being the index column).

I then want to display something like this:

BLOCK NAME #1 (being data from column bwblock_name)

[No files assigned, display block name only]

BLOCK NAME #2

1st file assigned to Block #2

2nd file assigned to Block #2

BLOCK NAME #3

1st file assigned to Block #3

2nd file assigned to Block #3

etc...

The code I have below displays everything I need it to, but lists the files under the first block, not the third where it actually belongs. How do I assign the files to display under the correct block? It obviously has something to do with lining up block.bwblock_id and files.bwblock_id but I just can't figure out what that is.

I've tried a LEFT JOIN statement but the below MySQL is the closest I've come to getting what I want.

I select the blocks data first:

$query_RS_Blocks = "SELECT * FROM blocks WHERE bwblock_year = $variable ORDER BY bwblock_id ASC"
$row_RS_Blocks = mysql_fetch_assoc($RS_Blocks);

Then I select the applicable files:

"SELECT * FROM files WHERE bwblock_id IN (SELECT bwblock_id FROM blocks WHERE bwblock_year = $variable) ORDER BY file_name ASC"
$row_RS_Files = mysql_fetch_assoc($RS_Files);

My stripped-down PHP display code is:

do {
echo $row_RS_Block['block_name']; 
do {
 echo $row_RS_Files['file_name'];
   } 
while ($row_RS_Files= mysql_fetch_assoc($RS_Files));
          }
while ($row_RS_Blocks = mysql_fetch_assoc($RS_Blocks));

I've also tried changing the last line to:

while (($row_RS_Blocks = mysql_fetch_assoc($RS_Blocks)) && ($row_RS_Blocks['bwblock_id'] == $row_RS_Files['bwblock_id']));

Then I get the first file inserted under the first block, and the second file under the second block. (Note there are only two files returned in that particular file query. I imagine it would assign each block with a single file infinitely.)

My mind is mush right now but if I have omitted any necessary info please advise and I will amend asap.

Can you try this select? And let me know if it would work.

SELECT b.bwblock_id, b.bwblock_year, b.bwblock_name, f.file_id, f.file_name 
FROM blocks AS b
LEFT JOIN files as f
ON b.bwblock_id=f.bwblock_id;

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