0

I have a small problem. I have two tables in a database:

[place]                        [client]

id     country                 id     name     id_place
--------------                 ------------------------
1      Canada                  1      Mike     1
2      USA                     2      Susan    1
3      China                   3      Juan     3
                               4      Nelly    2
                               5      Kevin    3

Using a SQL query:

SELECT 
    place.country, cliente.name 
FROM 
    place, client 
INNER JOIN 
    client ON place.id = client.id_place

and I show the results using:

while ($list = mysql_fetch_array($query))
{
     echo $list['contry']." | ".$list['name'];
}

And the results are:

Canada | Mike
Canada | Susan
USA    | Nelly
China  | Juan
China  | Kevin

So far so good. My problem is I want to show the results as follows:

<h1> Canada: <h1>
<h3> -Mike <h3>
<h3> -Susan <h3>

<h1> USA: <h1>
<h3> -Nelly <h3>

<h1> China: <h1>
<h3> -Juan <h3>
<h3> -Kevin <h3>

How I can do this? Help me please... Thanks!

1 Answer 1

1

This should work:

$h1 = NULL;

while ( $list = mysql_fetch_array($query) ) {
    if($h1 <> $list['contry']) {
        echo "<h1>" . $list['contry'] . ":</h1>\n";

        $h1 = $list['country'];
    }

    echo "<h3>- " . $list['name'] . "</h3>\n";
}

$h1 is initialized as NULL. When the loop begins, it checks whether $h1 is equal to the $list['country']. If it is not, it will output the header for the country and set them equivalent so that it is not repeated.

You should also stop using mysql_ functions as they are being deprecated and use mysqli_ or PDO instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.