如何添加表值然后显示我的网站上的总数

时间:2013-05-24 04:05:59

标签: mysql database html5

我想一起添加两个表格总计,然后将它放在我的网站上这里是我尝试过的代码。

        <?php
         $host     = "localhost";
             $username = "runerebe_online";
             $password = "***";
             $db_name  = "runerebe_online";
         mysql_connect("$host", "$username", "$password") or die (mysql_error ());
         mysql_select_db("$db_name") or die(mysql_error());
             $host     = "localhost";
             $username = "runerebe_online2";
             $password = "***";
             $db_name  = "runerebe_online2";
          mysql_connect("$host", "$username", "$password") or die (mysql_error ());
          mysql_select_db("$db_name") or die(mysql_error());
          $total = "SELECT (online + online2)";
           $rs = mysql_query($total);
          while($row = mysql_fetch_array($rs)) {      
            echo $row['total'];
          }
           mysql_close();
      ?>    

这是我使用此

时的错误打印
    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/runerebe/public_html/home/index.php on line 63

这是第63行及其包含的内容

    63: while($row = mysql_fetch_array($rs)) {    
    64:       echo $row['total'];
    65: }

1 个答案:

答案 0 :(得分:1)

您的查询无效。这就是为什么mysql_query()失败并返回FALSE而不是mysql_fetch_array()成功所需的资源的原因。

如果您需要从两个不同的数据库中读取两个值,并且如果用户具有允许在两个数据库上执行select的权限并且当前已连接到数据库online,则可以使用此类语句执行此操作

SELECT
    (SELECT SUM(o2.columnname) FROM runerebe_online2.tablename o2) + 
    (SELECT SUM(columnname) FROM tablename) TOTAL

否则你需要在php中分别检索两个值,如

//Connect and get a value from db 'runerebe_online'
...
$db_name  = "runerebe_online";
$link1 = mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db($db_name, $link1) or die(mysql_error());
$sql = "SELECT SUM(columnname) subtotal FROM tablename"
$result = mysql_query($total, $link1);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$subtotal1 = $row['subtotal'];
mysql_free_result($result);
mysql_close($link1);

//Connect and get a value from db 'runerebe_online2'
...
$db_name  = "runerebe_online2";
$link2 = mysql_connect("$host", "$username", "$password") or die (mysql_error ());
mysql_select_db("$db_name", $link2) or die(mysql_error());
$sql = "SELECT SUM(columnname) subtotal FROM tablename"
$result = mysql_query($total, $link2);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$subtotal2 = $row['subtotal']
mysql_free_result($result);
mysql_close($link1);

$total = $subtotal1 + $subtotal2;
echo $total;
...