Distinguishing between rows from a union query.

Hello all, I’m trying to use a union query to fetch rows from unrelated tables, and display all the rows, sorting by some common critarion (in this case, the time the entry was posted/registered/uploaded). The tables are named publications and images. So here is the select statement and associated code:

[php]

<?php //Connect to database require("config.php"); //Query the database. $query = "SELECT publication AS a, cartegory AS b, pub_time AS c FROM publications UNION ALL SELECT image AS a, image_cartegory AS b, image_time AS c FROM images ORDER BY c DESC"; $result = mysql_query($query); if(!$result) { die('

Could not retrieve the data because: ' . mysql_error(). '

'); // Handle as desired }else{ //If query is valid. if(mysql_num_rows($result) > 0){ while ($row = mysql_fetch_assoc($result)){ echo "

".$row['a']."

"; }//End of while loop }else{//If no rows were returned echo "no rows returned"; } }//Closes if query is valid statement. ?>

[/php]

Well as expected, all the contents from the image and publication columns are displayed in the order specified. But now my problem is, I want to be able to distinguish between the rows, depending on their table of origin, in order to format them differently. For example, let’s say I want the rows from the image table to be printed out with one font style and the rows from the publications table to be printed with a different font style, how do I go about that?

So far I have tried things like:

[php]

//For the sake of simplicity, I won’t include the html formatting here

while ($row = mysql_fetch_assoc($result)){ if ($row[‘a’] == $row[‘publication’]){echo $row[‘publication’];} else{echo $row[‘image’];}

//OR

if (‘a’ == ‘publication’){echo $row[‘a’];} elseif (‘a’ == ‘image’){echo $row[‘a’];}

[/php]

Well I hope you get the idea what I’m trying to achieve here. So far, these and similar lines I’ve tried only yield a blank page. I’m starting to wonder if it is even possible to format the rows differently based on their table of origin. So folks, please tell me if there is anyway what I’m trying to do can be done.

You can modify SELECT sentence including some text

try for example:

[php]//Query the database.
$query = “SELECT publication AS a, cartegory AS b, pub_time AS c,‘publication’ as tableType FROM publications
UNION ALL
SELECT image AS a, image_cartegory AS b, image_time AS c,‘images’ as tableType FROM images ORDER BY c DESC”;[/php]

In php can check this value :

[php]while ($row = mysql_fetch_assoc($result)){
if ($row[‘tableType’] == ‘publication’){
echo ‘publication ->’.$row[‘a’];
} else{
echo ‘image ->’.$row[‘a’];
}
}[/php]

But really always echo the same you can :
[php]while ($row = mysql_fetch_assoc($result)){
echo $row[‘a’];

}[/php]

@kikesv, thanks for the suggestion. seems rather plausible and i’m going to try it out. i’ve had similar suggestions from other forums.

Sponsor our Newsletter | Privacy Policy | Terms of Service