使用 php 计算数据库 table 中的特定行

calculations on specific rows in table of database using php

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

这是显示来自我的数据库

的table的部分

<?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>";
      
  }
?>

只要保证 table1 会return 1行,这里有一个建议:

  • 不用while循环取内容,只取行,所以table1的内容在$row1
  • foreach($row2 as $cell2) 更改为 foreach($row2 as $key=>$value) 格式。这样你就会得到$row1
  • 中对应元素的索引
  • foreach($row2 as $key=>$value)循环中,使用累加器计算"Column I"。例如。 $tot += $value * $row1[$key]
  • "echo" </tr>
  • 之前的累加器列

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

可以遍历第二个table,嵌套循环计算总和:

$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>";  
}