Combining 2 Mysql query results

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
sandysmith
Forum Newbie
Posts: 1
Joined: Sun Sep 04, 2011 11:16 pm

Combining 2 Mysql query results

Post by sandysmith »

Hi All,

Below is my code to add the two different query results into one. This is working fine when both the queries have same no.of rows.

eg: row1 = 1 2 3 (Query1)

row2 = 3 5 5 (Query2)

o/p: 4 7 8

Let's say, I have few rows which are not exactly matched with first query.

eg: row1 = 1 2 3 2 (Query1)

row2 = 3 empty empty 5 (Query2)

o/p : 4 2 3 7 (I want the o/p to be like this)

empty means there is no data from the second query.

In my while, && working fine when the 2 queries have same no.of rows.


while (($row1 = mysql_fetch_assoc($rs1)) && ($row2 = mysql_fetch_assoc($rs2)))
{


$strHtml .= "<tr>";

$strHtml .= "<td align=center colspan=3>".($row1['Calls']+$row2['Calls'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['actual_duration(min)A']+$row2['actual_duration(min)A'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['call_usage']+$row2['call_usage'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['disconnection_charge']+$row2['disconnection_charge'])."</td>";
$strHtml .= "<td align=center colspan=3>".($row1['total_revenue']+$row2['total_revenue'])."</td>";

$strHtml .= "</tr>";

}

Is the while loop i am using correct or there is any other better solution for this?

please help me, Thanks in advance.
User avatar
manohoo
Forum Contributor
Posts: 201
Joined: Wed Dec 23, 2009 12:28 pm

Re: Combining 2 Mysql query results

Post by manohoo »

I pressume that you mean "columns"... Maybe you can get some ideas from this:

Code: Select all


$a = array(1,2,3,4);
$b = array(4,5,null, null);

if(sizeof($a) == sizeof($b)) {

	for ($i=0; $i<sizeof($a); $i++) {
		$total[] = $a[$i] + $b[$i];
	}
}

$total is now an array with these values (5,7,3,4)
User avatar
ok
Forum Contributor
Posts: 393
Joined: Wed May 31, 2006 9:20 am
Location: The Holy Land

Re: Combining 2 Mysql query results

Post by ok »

Have you tried to do this using SQL?
Post Reply