How do I separate output from SQL tables using SQL UNION?

advertisements

I have several tables in one database, with each table containing the exact same column names. I'm using SQL UNION in order to pull every record from all of those tables, and output the records onto a web page. Each record is output between a div with an ID of 'contributors.'

What I am ultimately tying to do is set some sort of separation between each table that is being output, so that I don't have every record within a table seamlessly running into the next table.

I tried to echo a div before the 'contributors' div, but that did not work. Does anyone have any idea how I can output data from issue1, then create a heading to below to separate issue1 from issue2?

<?php

$res=mysql_query('
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue1 UNION ALL
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue2 UNION ALL
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue3
');
if (!$res) { // add this check.
    die('Invalid query: ' . mysql_error());
}
while($row=mysql_fetch_array($res))
{
$cont_img_path = $img_path.end(explode('/', $row['Picture']));
if(file_exists($cont_img_path))
{
?>
    <div class="contributors">
        <h6><?php echo $row['First']; ?> <?php echo $row['Last']; ?></h6>
        <h2 style="color:#ffffff;"><em><?php echo $row['Title']; ?></em></h2>
        <p style="color:#ffd997;"><?php echo $row['Genre']; ?></p>

<h3 class="ctr-image"><a href="<?php echo $row['Picture']; ?>" id="3e-fancybox" name="<?php echo $row['First'] .' '. $row['Last']; ?>" StoryLink="<?php echo $row['StoryLink']; ?>" Ptitle="<?php echo $row['Title']; ?>" genre="<?php echo $row['Genre']; ?>" about="<?php echo str_replace('"', '"', ($row['About'])); ?>" WebLink="<?php echo $row['Link']; ?>"><img src="<?php echo $row['Picture']; ?>" alt="<?php echo $row['ALT']; ?>"></a></h3>
    </div>
<?php } } ?>


Notwithstanding that if you want three separate results sets, it makes more sense to use AJAX and make three separate requests, here is a solution:

$res = mysql_query('
SELECT
      'Issue1' as context,
      First,
      Last,
      Title,
      StoryLink,
      Genre,
      About,
      Link,
      Picture,
      ALT
FROM
    issue1
UNION ALL
SELECT
      'Issue2' as context,
      First,
      Last,
      Title,
      StoryLink,
      Genre,
      About,
      Link,
      Picture,
      ALT
FROM
    issue2
UNION ALL
SELECT
      'Issue3' as context,
      First,
      Last,
      Title,
      StoryLink,
      Genre,
      About,
      Link,
      Picture,
      ALT
FROM
      issue3
)';

This solves the question, as asked, however I'm not convinced your database structure is correct to begin with.