You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP表单无法将单选按钮值存入cand表Vcount列且新增空白行如何解决

修复方案

核心问题

  • 前端选项类型和参数错误:你需要的是单选功能却用了checkbox,所有选项name属性重复且value固定为字符串vote,提交时无法传递选中的候选人ID,后端拿到的$vote是字符串vote,转为数字存入数字类型的Vcount字段自然变成0。
  • 数据库操作逻辑错误:投票是给已存在的候选人票数累加,应该用UPDATE语句更新现有行,你用INSERT必然每次新增空白行。
  • 存在SQL注入风险,直接拼接用户输入的参数到SQL语句中极易被攻击。

修复后的代码

前端表单部分

<body>
    <div>
        <form id="login" action="#" method="POST" >
            <input type="text" name="Name" required placeholder="Name" class="input"><br />
                <div>
                    <?php
                        $sql = "SELECT * FROM cand ";
                        $result  = $con->query($sql);
                        if ($result->num_rows > 0) {
                            echo "<table border='2' class='container2'>
                            <tr>
                            <th>Number</th>
                            <th>Name</th>
                            <th>Photo</th>
                            <th>Position</th>
                            <th>Voters</th>
                            <th>Vote</th>
                            </tr>";
                            while($row = $result->fetch_assoc()){
                                echo "<tr>
                                <td>" . $row["ID"]."</td>
                                <td>" . $row["cName"]. "</td>
                                <td><img src='img/" . $row["cPic"]. "'></td>
                                <td>" . $row["Position"]."</td>
                                <td>" . $row["Vcount"]."</td>
                                <!-- 改为单选按钮,value绑定候选人ID,name统一为vote_id -->
                                <td><input type='radio' name='vote_id' value='".$row["ID"]."' required></td>
                                </tr>";
                            }
                            echo "</table>";  
                        }
                    ?>
    </div>
            <button name="login" type="submit">Vote</button> 
        </form>
    </div>
</body>
</html>

后端处理部分

<?php 
if(isset($_POST['login']) && isset($_POST['vote_id'])){
    $vote_id = intval($_POST['vote_id']); // 转整数过滤参数
    // 用UPDATE语句给对应候选人票数+1
    $sql = "UPDATE cand SET Vcount = Vcount + 1 WHERE ID = ?";
    // 预处理语句防注入
    $stmt = $con->prepare($sql);
    $stmt->bind_param("i", $vote_id);
    $stmt->execute();
    $stmt->close();
}
?>

内容的提问来源于stack exchange,提问作者Zets

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:15:06