【问题标题】:calculations on specific rows in table of database using php使用php计算数据库表中的特定行
【发布时间】:2019-08-31 19:09:09
【问题描述】:

我正在开发一个管理学校教师的 php 项目。但我遇到了一个问题,我的数据库中有两个表,第一个 T1 在行上,第二个 T2 有多行,但它们的列号相同。在第三个表 T3 中,我需要用总计填充一列 (T1 的单元格1*T2 的单元格1) + (T1 的单元格2*T2 的单元格2)+ (T1 的单元格3*T2 的单元格3)....到最后一列 我只是找不到正确的方法来做到这一点

这是显示我的数据库中的表的部分

<?php
$host="localhost";
$user="root";
$pass="";
$bdd="test";
$cnx=mysql_connect($host,$user,$pass);
if(!$cnx)
	echo"connexion echouee"."</br>";
else
	echo"connexion reussie"."</br>";

if (mysql_select_db($bdd))
	echo"base de donnees trouvee"."</br>";
else
	echo"base de donnees introuvable"."</br>";

  $req1="SELECT * FROM `table1`";
  $res1=mysql_query("$req1");
  // printing table rows
  while($row1 = mysql_fetch_row($res1))
  {
      echo "<tr>";
      foreach($row1 as $cell1)
          echo "<td>|$cell1|</td>";
      echo "</tr>";  echo"</br>";
  }
echo "_____</br>";
  $req2="SELECT * FROM `table2`";
  $res2=mysql_query("$req2");
  // printing table rows
  while($row2 = mysql_fetch_row($res2))
  {
      echo "<tr>";
      foreach($row2 as $cell2)
          echo "<td>|$cell2|</td>";
      echo "</tr>";echo"</br>";
      
  }
?>

【问题讨论】:

  • 分享你的代码吗?
  • 那么你打算通过 PHP 还是 MySQL 来实现呢?
  • 我打算使用php,但我需要mysql来获取表格的内容
  • 值得注意的是,mysql_* 系列函数不再存在于任何受支持的 PHP 版本中。您可能应该使用PDO 或至少mysqli。任何使用mysql_connect 的教程都已经过时了。

标签: php mysql calculation


【解决方案1】:

只要 保证 table1 将返回 1 行,这里有一个建议:

  • 不使用while循环获取内容,只获取行,所以table1的内容在$row1
  • foreach($row2 as $cell2) 更改为foreach($row2 as $key=&gt;$value) 格式。这样,您将在$row1 中获得相应元素的索引
  • foreach($row2 as $key=&gt;$value) 循环内,使用累加器计算“I 列”。例如。 $tot += $value * $row1[$key]
  • “回显”&lt;/tr&gt; 之前的累加器列

您可能还想在$row1 循环中添加一个空的&lt;td&gt;,以确保所有行的列数相同。

【讨论】:

    【解决方案2】:

    您可以遍历第二个表并使用嵌套循环计算总计:

    $res1 = mysql_query("SELECT * FROM `table1`");
    $res2 = mysql_query("SELECT * FROM `table2`");
    
    $row1 = mysql_fetch_row($res1);
    $row = 0;
    
    // for each row of second table
    while ($row2 = mysql_fetch_row($res2)) {
        $row++;
        $total = 0;
    
        // for each column of first table's row
        foreach ($row1 as $index => $table1RowValue) {
            // get value of same column in the second table's row
            $table2RowValue = $row2[$index];
    
            // calculate aggregated value
            $total += $table1RowValue * $table2RowValue;
        }
    
        // print result
        echo "Line $row: $total</br>";  
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    相关资源
    最近更新 更多