我从php中检索mysql数据库中的一些数据。我写了以下代码。但 而不是重复相同的代码,有没有其他方法可以做到这一点?因为我需要编写相同的代码超过50次。 我也用于循环。但我得到了正确的答案。但由于for循环的答案也重复如下
但正确的输出应为
第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);
答案 0 :(得分:-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);