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

PHP+MySQL统计两表指定barcode行数相等才可插入的异常问题求助

问题排查

以下是你代码里的几处核心错误:

  • 校验逻辑触发条件完全写反:你把统计两张表行数的校验代码放在了if(!isset($_POST['barcode']))判断里,只有当POST参数中不存在barcode的时候才会执行校验逻辑,实际业务中barcode肯定是会提交的,所以校验代码永远不会运行。
  • COUNT结果取值逻辑错误:mysqli_num_rows()返回的是查询结果集的行数,你执行COUNT查询的时候,无论统计的数值是多少,结果集永远只有1行,所以用这个方法拿不到统计的数量。正确做法是从结果集中取出COUNT的返回值,同时你之前直接把查询结果对象$result_barcodeOutEll和数值做对比,本身也属于语法错误。
  • 插入逻辑和校验逻辑完全独立:你没有把校验通过作为插入的前置判断条件,只要barcode参数存在就会直接执行插入操作,前面的校验结果完全不会影响插入逻辑。
  • 额外安全问题:直接把用户提交的$barcode拼接到SQL语句中,存在严重的SQL注入风险,建议使用预处理语句处理参数。
修正后代码
<?php
$msg = '';
if(isset($_POST['rogzit_in'])) {
    // 先校验barcode是否存在
    if(!isset($_POST['barcode']) || empty(trim($_POST['barcode']))) {
        $msg = '<h4 class="col-12 text-center mb-3 text-danger">barcode参数不能为空!</h4>';
    } else {
        $barcode = trim($_POST['barcode']);
        // 统计log_in中对应barcode的数量
        $sql_in = "SELECT COUNT(barcode) as cnt FROM log_in WHERE barcode = ?";
        $stmt_in = mysqli_prepare($dbCon, $sql_in);
        mysqli_stmt_bind_param($stmt_in, "s", $barcode);
        mysqli_stmt_execute($stmt_in);
        $res_in = mysqli_stmt_get_result($stmt_in);
        $count_in = mysqli_fetch_assoc($res_in)['cnt'];
        
        // 统计log_out中对应barcode的数量
        $sql_out = "SELECT COUNT(barcode) as cnt FROM log_out WHERE barcode = ?";
        $stmt_out = mysqli_prepare($dbCon, $sql_out);
        mysqli_stmt_bind_param($stmt_out, "s", $barcode);
        mysqli_stmt_execute($stmt_out);
        $res_out = mysqli_stmt_get_result($stmt_out);
        $count_out = mysqli_fetch_assoc($res_out)['cnt'];

        // 判断数量是否相等,相等才允许插入
        if($count_in == $count_out) {
            $sql_insert = "INSERT INTO log_in(barcode) VALUES (?)";
            $stmt_insert = mysqli_prepare($dbCon, $sql_insert);
            mysqli_stmt_bind_param($stmt_insert, "s", $barcode);
            if(mysqli_stmt_execute($stmt_insert)) {
                echo '<script type="text/javascript">window.location = "home.php/";</script>';
                exit();
            } else {
                $msg = '<h4 class="col-12 text-center mb-3 text-danger">插入失败,请重试!</h4>';
            }
        } else {
            $msg = '<h4 class="col-12 text-center mb-3 text-danger">Már bejelntkezett!</h4>';
        }
    }
}
?>

内容的提问来源于stack exchange,提问作者Tóth László

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 22:45:09