Re: Merge result set of query?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Jochem Maas wrote:
Martin Norland wrote:

ioannes wrote:

My first attempt was to use $result=array_merge($result1,$result2) - doesn't work. 'not a valid resource'

I have two databases with different connections, so MySQL UNION query would not work.

How do I merge the result set of the queries in that case?



You're going to have to merge the results within PHP.

"not a valid resource" is an error you get when you try to read from a result set and what you pass it isn't a resource for a result set.

I think you're doing something along the lines of:

$result1 = query_database_one($somequery);
$result2 = query_database_two($someotherquery);
$result = array_merge($result1, $result2);
while (mysql_fetch_row($result)) {


while reading I thought, would this:

while (($row = mysql_fetch_row($result)) || ($row = mysql_fetch_row($result2)))
{
// just do it. â
}



.. work (due to shortcircuiting)? and how ugly is it?

    // foo
}


That would work if you just wanted to iterate over both resultsets and do the same thing, yes. Say, if you had lists of users who signed up for something in two separate databases, you could print them all out with that. Since he said union and not join - that is probably his intention.


I can't decide if that code is beautiful or horribly ugly though... I would have to say it's beautiful so long as the 'just do it' is very short - if the 'just do it' should be a function - then you should just suck it up and do two while's. Also, for every result in $result2, you have to poke at the first database and say "any more yet?", which is hackish.

slick 'obfuscated perl' entry type fix though :) [okay, it's not obfuscated in the traditional sense]

cheers,
--
- Martin Norland, Sys Admin / Database / Web Developer, International Outreach x3257
The opinion(s) contained within this email do not necessarily represent those of St. Jude Children's Research Hospital.


--
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux