Im having trouble with a sql join involving a union. I’m trying to pull a COUNT and a field from 2 tables but getting an error.
The query:
$sql_result7 = mysql_query("(SELECT COUNT (*) as alertcount, date as alertdate FROM alerts WHERE to_id='$id' AND date > '$lastcheck') UNION (SELECT COUNT (*) as mailcount, date maildate FROM mobmail WHERE to_id='$id' AND to_del=0 AND seen = '0')", $db);
$rs7 = mysql_fetch_array($sql_result7);
$alerts = $rs7[alertcount];
$mails = $rs7[mailcount];
$last_alert = $rs7[alertdate];
$last_mail = $rs7[maildate];
Is it something to do with the date as alertdate part?
The error im getting is:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource
Besides the space between
COUNTand(*), there is another issue. You can’t use$rs7[mailcount]nor$rs7[maildate]in your PHP code because your query is equivalent to:and will return two rows and only 2 columns:
Two ways to solve this problem:
Either keep the query (changing the
UNIONtoUNION ALLto ensure that you always get 2 rows) and chnage the PHP to use the 2 rows.Or change the query to: