【问题标题】:How would I add to table values then show the total on my website我将如何添加到表值然后在我的网站上显示总数
【发布时间】:2013-05-24 04:05:58
【问题描述】:

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

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

【问题讨论】:

  • 在 php.ini 中某处有一个“计数”函数。这应该有点帮助
  • 您的查询无效SELECT (online + online2)。你想选择什么?
  • 我想从 online 中选择值 * 并将其添加到 online2 的值中
  • online和online2是两个数据库还是一个数据库两个表?

标签: mysql database html


【解决方案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;
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2017-05-20
    • 2017-12-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多