从2个表中选择mysql_fetch_assoc查询

时间:2012-12-28 16:07:17

标签: php mysql

  

可能重复:
  Warning: mysql_fetch_* expects parameter 1 to be resource, boolean given error

这有什么问题?前2个选择工作正常,另外2个返回此错误:

  

警告:mysql_fetch_assoc()期望参数1为资源,布尔值为

<?php 
$result=mysql_query("SELECT count(*) as total from urls WHERE username = '$username' AND approved = 'yes' ");
  $data=mysql_fetch_assoc($result);
echo $data['total'];?></td>

 <td><?php 
$result2=mysql_query("SELECT count(*) as total2 from urls WHERE username = '$username' AND approved = 'no' ");
  $data2=mysql_fetch_assoc($result2);
echo $data2['total2'];?></td>

  <td><?php 
$result3=mysql_query("SELECT count(*) as total3 from buy WHERE username = '$username' AND status = 'active' ");
  $data=mysql_fetch_assoc($result3);
echo $data['total3'];?></td>

  <td><?php 
$result4=mysql_query("SELECT count(*) as total4 from buy WHERE username = '$username' AND status = 'complete' ");
 $data=mysql_fetch_assoc($result4);
echo $data['total4'];?></td>

1 个答案:

答案 0 :(得分:0)

您可以在一个查询中执行此操作:

SELECT
  SUM(CASE WHEN approved = 'yes'      THEN 1 ELSE 0 END) AS Total1,
  SUM(CASE WHEN approved = 'no'       THEN 1 ELSE 0 END) AS Total2,
  SUM(CASE WHEN status   = 'active'   THEN 1 ELSE 0 END) AS Total3,
  SUM(CASE WHEN status   = 'complete' THEN 1 ELSE 0 END) AS Total4
FROM urls 
WHERE username = '$username';
相关问题