当我的输入数据来自循环时,如何使用array_sum添加输入值


How to add input values using array_sum, when my input data came from a loop?

我正在为不同的问题类别(类别:英语、数学、编程等)做一个问答生成器,我必须为每个类别设置项目数。

我使用这段代码从tbl_category:中检索数据

SetItemLimit.php

<?php
$con=mysqli_connect("localhost","root","admin","learning_assessment") or die("Cannot connect to database!");
$sql="select * from tbl_category;";
$rs=mysqli_query($con,$sql);
$rows=mysqli_fetch_array($rs);
?>
<html>
<head></head>
<body>
<form action="SetItemLimit.php" method="post">
<table border="1">
<tr>
<th>Category</th>
<th>Number of Items</th>
</tr>
<?php do{?>
<tr>
<td><input type="text" value="<?php echo $rows['category'];?>" readonly="readonly" /></td>
<td><input type="text" name="perCatLimit" /></td>
</tr>
<?php }while($rows=mysqli_fetch_array($rs));?>
</table>

TOTAL NUMBER OF THE TEST ITEMS: <input type="text" name="numQ"/><br />
<input type="submit" name="SetItemLimit" value="SET ITEM LIMIT" />
</form>
</body>
</html>

我想做的是,当我为每个类别设置项目数量并单击提交按钮(SetItemLimit)时,这些值将被相加并显示在文本框(numQ)中。

<?php
if(isset($_POST['SetItemLimit'])){
}

我能用吗

 array_sum()

您需要将perCatLimit设为数组输入,以便perCatLimit[]。见下文:

<?php
    if(isset($_POST['perCatLimit'])){
            $setLimit = array_sum($_POST['perCatLimit']);
        }
    $con    =   mysqli_connect("localhost","root","admin","learning_assessment") or die("Cannot connect to database!");
    $sql    =   "select * from tbl_category;";
    $rs     =   mysqli_query($con,$sql);
    $rows   =   mysqli_fetch_array($rs); ?>
<html>
<head>
</head>
<body>
<form action="SetItemLimit.php" method="post">
    <table border="1">
        <tr>
            <th>Category</th>
            <th>Number of Items</th>
        </tr>
        <?php do{?>
        <tr>
            <td><input type="text" value="<?php echo $rows['category'];?>" readonly="readonly" /></td>
            <td><input type="text" name="perCatLimit[]" /></td>
        </tr>
        <?php }while($rows = mysqli_fetch_array($rs));?>
    </table>
    TOTAL NUMBER OF THE TEST ITEMS:
    <input type="text" <?php echo (isset($setLimit) && is_numeric($setLimit))? 'value="'.$setLimit.'"':''; ?> name="numQ"/>
    <br />
    <input type="submit" name="SetItemLimit" value="SET ITEM LIMIT" />
</form>
</body>
</html>