PDA

View Full Version : Grab Table Name When Using A Union


ideffect
08-06-2009, 05:04 AM
Hey,

I am trying to build a search function for a website that is database driven. I need to search content on two tables. To do this, I used a union for the query. The problem is that I don't know how to grab the table's name. I need to know which table the data is coming from to know where to send the user.

Here is my current query...

$query_search = mysql_query("SELECT id,title FROM articles WHERE MATCH(articles.title,articles.content) AGAINST ('$search_query')
UNION
SELECT id,title FROM main_content WHERE MATCH(main_content.title,main_content.content) AGAINST ('$search_query')") or die(mysql_error());


I also tried..

$query_search = mysql_query("SELECT id AS tablename,title FROM articles WHERE MATCH(articles.title,articles.content) AGAINST ('$search_query')
UNION
SELECT id AS tablename2,title FROM main_content WHERE MATCH(main_content.title,main_content.content) AGAINST ('$search_query')") or die(mysql_error());



To check it, I am using...

while ($object_search = mysql_fetch_object($query_search)) {
foreach ($object_search as $a => $b) {
echo "$a->$b<br/>";
}
}


Any help would be greatly appreciated.
Thanks!

ckeyrouz
08-06-2009, 05:08 AM
Just add the name of the table statically as shown in the query before and you can read the field tableName the same way you would read the field id or title.

SELECT id,title, 'articles ' tableName FROM articles WHERE MATCH(articles.title,articles.content) AGAINST ('$search_query')
UNION
SELECT id,title, 'main_content' tableName FROM main_content WHERE MATCH(main_content.title,main_content.content) AGAINST ('$search_query')

ideffect
08-06-2009, 08:11 AM
Thank You!!

I guess I still have a lot to learn...