-1

我想将两个表格总计相加,然后将其放在我的网站上,这是我尝试过的代码。

        <?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: }
4

1 回答 1

1

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

如果您需要从两个不同的数据库中读取两个值,并且如果用户有权在两个数据库上进行选择并且当前连接到数据库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;
...
于 2013-05-24T04:24:40.127 回答