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

如何在PHP中结合变量与下划线使用LIKE关键字查询水库数据?

问题分析与解决方案

核心问题

  1. 变量解析错误:你最初的SQL语句中'$resreq__'会被PHP错误解析——下划线是变量名的合法字符,PHP会把$resreq__当成一个完整变量,而非$resreq拼接两个下划线,导致SQL中的匹配条件完全不符合预期,最终返回空结果。
  2. 通配符匹配范围过大:使用%通配符会匹配任意长度的后缀,自然会包含其他类别中前缀相似的水库编码。
  3. 严重的SQL注入风险:直接将用户输入的discode和restype拼接到SQL语句中,属于高危操作,极易被利用篡改数据库。

针对性解决方案

根据水库编码的格式,分两种场景给出修复代码:

场景1:水库编码格式为「前缀+固定长度后缀」

比如$resreq是前4位,后面固定跟2位编号,用_通配符匹配固定长度的后缀:

<?php
if (isset($_POST['submit1'])) {
    $errors = array();

    // 优先用$_POST获取表单数据,避免REQUEST带来的安全隐患
    $discode = $_POST['discode'] ?? '';
    $restype = $_POST['restype'] ?? '';

    $resreq = $discode . $restype;
    // 构造匹配规则:前缀+2个任意字符(根据实际后缀长度调整下划线数量)
    $matchPattern = $resreq . '__';

    // 使用预处理语句彻底规避SQL注入
    $sql = "SELECT * FROM resourcelist WHERE rescode LIKE ? ORDER BY rescode";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("s", $matchPattern);
    $stmt->execute();
    $result = $stmt->get_result();
?>
<form action="" method="post" enctype="multipart/form-data" >       
<table class="table table-hover table-striped table-responsive">
    <thead>
        <tr>
        <th>ID</th>
        <th>Resource Type</th>
        <th>Reservoir Name</th>
        <th>Reservoir Code</th>
    </tr>
    </thead>
    <tbody> 
        <?php
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
        ?>
                    <tr>
                    <td><?php echo htmlspecialchars($row['id']); ?></td>         
                    <td><?php echo htmlspecialchars($restype); ?></td>
                    <td><?php echo htmlspecialchars($row['cultsysname']); ?></td>
                    <td><?php echo htmlspecialchars($row['rescode']); ?></td>
                    </tr>                       
        <?php       
                }
            } else {
                echo '<tr><td colspan="4">未找到匹配的水库</td></tr>';
            }
        ?> 
        </tbody>
        </table>
    </form>    
<?php
}
?>

场景2:水库编码的前缀长度固定(仅匹配前缀完全一致的编码)

比如$resreq是固定长度的「地区码+类型码」,用LEFT()函数精确匹配前缀:

<?php
if (isset($_POST['submit1'])) {
    $errors = array();

    $discode = $_POST['discode'] ?? '';
    $restype = $_POST['restype'] ?? '';
    $resreq = $discode . $restype;
    $prefixLength = strlen($resreq);

    // 精确匹配编码的前N位等于前缀,避免%通配符的过度匹配
    $sql = "SELECT * FROM resourcelist WHERE LEFT(rescode, ?) = ? ORDER BY rescode";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("is", $prefixLength, $resreq);
    $stmt->execute();
    $result = $stmt->get_result();
?>
<!-- 后续表格输出部分和场景1一致,省略重复代码 -->
<?php
}
?>

额外优化点

  • 用htmlspecialchars()包裹输出内容,防止XSS攻击。
  • 增加无匹配结果时的提示,提升用户体验。
  • 用$_POST替代$_REQUEST,仅接收POST提交的表单数据,缩小输入范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:05:19