-1

我正在从 php 的 mysql 数据库中检索一些数据。我写了以下代码。但是除了 重复下面的相同代码之外,还有其他方法可以做到这一点吗?因为我需要编写相同的代码超过 50 次。我也使用了for循环。但我得到了正确的答案。但是由于for循环的答案也重复如下

  • 第 1 章大纲- 8
  • 第 1 章演示幻灯片 - 8
  • 第 1 章示例活动 - 8
  • 自我评估测试 1- 0
  • 第一章大纲- 6
  • 第 1 章演示幻灯片 - 6
  • 第 1 章示例活动 - 6
  • 自我评估测试 1- 0
  • 第一章大纲- 11
  • 第 1 章演示幻灯片 - 11
  • 第 1 章示例活动 - 11 自我评估测试 1- 0
  • 第一章大纲- 0
  • 第 1 章演示幻灯片- 0
  • 第 1 章示例活动 - 0
  • 自我评估测试 1-49

但正确的输出应该是

  • 第 1 章大纲- 8

  • 第 1 章演示幻灯片 - 6

  • 第 1 章示例活动 - 11

  • 自我评估测试 1-49

可能是我错误地使用了 for 循环括号,或者我的代码有什么问题? 请帮我。我是 php mysql 的新手,并从互联网课程中学习它。(程序是关于在学习管理系统中计算访问课程的次数)

<?php 
$con=mysqli_connect("localhost:3306","root","", "moodle");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$chap1outr="resource";
$chap1outr1="quiz";


for ($i=81; $i<=116; $i++)
{
    $result1 = mysqli_query ($con,"SELECT count(*) as counts FROM mdl_log WHERE  userid='2' and module='$chap1outr' AND cmid=$i") or die("Error: ".mysqli_error($con));

    while($row1= mysqli_fetch_array( $result1))
    {
        echo "Chapter 1 Outline". "- " . $row1['counts'];
        echo "<br>";
    }

    $result2 = mysqli_query ($con,"SELECT count(*) as counts1 FROM mdl_log WHERE  userid='2' and module='$chap1outr' AND cmid=$i") or die("Error: ".mysqli_error($con));


    while($row2= mysqli_fetch_array( $result2))

    {
        echo "Chapter 1 Presantation Slides". "- " . $row2['counts1'];
        echo "<br>";
    }

    $result3 = mysqli_query ($con,"SELECT count(*) as counts2 FROM mdl_log WHERE  userid='2' and module='$chap1outr' AND cmid=$i") or die("Error: ".mysqli_error($con));


    while($row3= mysqli_fetch_array( $result3))

    {
        echo "Chapter 1 Example Activity". "- " . $row3['counts2'];
        echo "<br>";
    }

    $result4 = mysqli_query ($con,"SELECT count(*) as counts3 FROM mdl_log WHERE  userid='2' and module='$chap1outr1' AND cmid=$i") or die("Error: ".mysqli_error($con));


    while($row4= mysqli_fetch_array( $result4))

    {
        echo "Self Assessment Test 1". "- " . $row4['counts3'];
        echo "<br>";
    }
}
mysqli_close($con);
4

1 回答 1

-1
<?php 
$con=mysqli_connect("localhost:3306","root","", "moodle");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$chap1outr="resource";
$chap1outr1="quiz";


for ($i=81; $i<=116; $i++)
{
    $result1 = mysqli_query ($con,"SELECT count(*) as counts FROM mdl_log WHERE  userid='2' and module='$chap1outr' AND cmid=$i") or die("Error: ".     mysqli_error($con));

    $row1= mysqli_fetch_array( $result1);
    echo "Chapter 1 Outline". "- " . $row1['counts']."<br>";
    echo "Chapter 1 Presantation Slides". "- " . $row1['counts']."<br>";
    echo "Chapter 1 Example Activity". "- " . $row1['counts']."<br>";
    echo "Self Assessment Test 1". "- " . $row1['counts']."<br>";


}
mysqli_close($con);
于 2013-07-26T09:39:18.470 回答