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

当$data['filename']为空时切换或隐藏图片的技术实现问询

解决方案

先修正原代码里的几个核心问题:

  • 循环中重复使用id="test",HTML规定id必须唯一,建议改用class
  • 原JS语法错误且逻辑冗余,直接用PHP后端判断更高效,无需前端处理
  • 存在严重SQL注入风险,必须用预处理语句替代直接拼接用户输入

方案1:当filename为空时替换为无PDF图标

通过PHP动态判断文件名是否有效,修改图片地址:

<table align="center" border="0" style="font-size: 14px;">
<?php
$idnum = $_POST['idnum'];
include "dbConn.php"; 
// 预处理语句防止SQL注入
$stmt = $db->prepare("select * from scan where idnum like ?");
$likeParam = "%$idnum%";
$stmt->bind_param("s", $likeParam);
$stmt->execute();
$records = $stmt->get_result();

while($data = mysqli_fetch_array($records))
{
    // 判断文件名是否为空(包含null、空字符串情况)
    $hasValidFile = !empty($data['filename']);
    $imgSrc = $hasValidFile ? "pdf.png" : "no-pdf.png";
    $fileUrl = $hasValidFile ? "https://mysite.co.za/image/" . htmlspecialchars($data['filename']) : "#";
?>
  <tr align="center">
    <td><?php echo htmlspecialchars($data['idnum']); ?>&nbsp;&nbsp;</td>
    
    <td class="pdf-container">
        <a href="<?php echo $fileUrl; ?>" target="popup" 
           onclick="<?php if($hasValidFile): ?>window.open('<?php echo $fileUrl; ?>','popup','width=600,height=600'); return false;<?php else: ?>return false;<?php endif; ?>">
            <img src="<?php echo $imgSrc; ?>" style="width:30px;height:40px;">
        </a>&nbsp;&nbsp;
    </td>
    
  </tr> 
<?php
}
$stmt->close();
?>
</table>

说明:

  • 用!empty()同时处理null和空字符串的情况
  • 文件名无效时,图片切换为no-pdf.png,并禁用链接点击事件
  • 用htmlspecialchars()输出用户数据,避免XSS攻击

方案2:当filename为空时隐藏PDF图标区域

直接通过PHP控制是否渲染图标模块,保持表格结构对齐:

<table align="center" border="0" style="font-size: 14px;">
<?php
$idnum = $_POST['idnum'];
include "dbConn.php"; 
$stmt = $db->prepare("select * from scan where idnum like ?");
$likeParam = "%$idnum%";
$stmt->bind_param("s", $likeParam);
$stmt->execute();
$records = $stmt->get_result();

while($data = mysqli_fetch_array($records))
{
    $hasValidFile = !empty($data['filename']);
?>
  <tr align="center">
    <td><?php echo htmlspecialchars($data['idnum']); ?>&nbsp;&nbsp;</td>
    
    <?php if($hasValidFile): ?>
    <td class="pdf-container">
        <a href="https://mysite.co.za/image/<?php echo htmlspecialchars($data['filename']); ?>" target="popup" 
           onclick="window.open('https://mysite.co.za/image/<?php echo htmlspecialchars($data['filename']); ?>','popup','width=600,height=600'); return false;">
            <img src="pdf.png" style="width:30px;height:40px;">
        </a>&nbsp;&nbsp;
    </td>
    <?php else: ?>
    <!-- 为空时留空td保持表格布局对齐 -->
    <td>&nbsp;&nbsp;</td>
    <?php endif; ?>
    
  </tr> 
<?php
}
$stmt->close();
?>
</table>

说明:

  • 通过if($hasValidFile)控制是否渲染PDF图标区域
  • 文件名无效时输出空td,避免表格结构错乱
  • 同样修复了SQL注入和XSS风险问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 04:23:19