按其他表格的标题对结果进行分组

I have two tables, one contains the page/heading number and the heading text, the other contains values to print under each heading:

Headings:

page | heading | text
1    | 1       | "heading 1"
1    | 2       | "heading 2"

Contents:

page | heading | contents
1    | 1       | "some stuff"
1    | 1       | "some more stuff"
1    | 2       | "some other stuff"

I want the results for page 1 to be:

heading 1
some stuff
some more stuff
heading 2
some other stuff

Augmented with HTML where needed.

Using two while loops with mysql_fetch_array() doesn't work because you have to fetch before you can check if it's under the correct heading. This means I miss the first entry of every next heading.

$query = "SELECT text,heading FROM headings WHERE page=".$page." ORDER BY heading ASC";
$headings = mysql_query($query) or die(mysql_error());
$query = "SELECT filename,heading FROM pictures WHERE page=".$page." ORDER BY heading ASC";
$pictures = mysql_query($query) or die(mysql_error());

while($heading = mysql_fetch_array($headings)){
echo $heading[0];
    while($image = mysql_fetch_array($pictures)){ # This skips entries because I have to check the contents themselves
        if($image[1] != $heading[1]){
            break;
        }
        echo $image[0];
    }
}

Is there any way to do this without running multiple queries for every heading? (There may be many on a page)

Just fetch all results into 2 arrays before iterating with while loops.

What you are looking for is a query with a JOIN in it.

I have assumed your database looks something like this: Fiddle

Included is the query you may be looking for