如何在PHP的href语句中传递两个字段作为查询字符串至目标页面
解决方案
1. 修改发送页链接,传递两个参数
原链接存在语法错误(/>a>需修正为</a>),同时要在查询字符串中添加Sec_Sub参数,建议用urlencode()处理参数值,避免特殊字符导致的链接异常:
while($row = mysqli_fetch_array($result)) { ?> <tr> <td><?php echo $row["Sec_No"]; ?></td> <td><?php echo $row["Sec_Sub"]; ?></td> <td><?php echo $row["Sec_Lec"]; ?></td> <td><a href="Theo_Entery_Sheet.php?Sec_No=<?php echo urlencode($row["Sec_No"]); ?>&Sec_Sub=<?php echo urlencode($row["Sec_Sub"]); ?>">Enter Marks</a></td> </tr> <?php }
2. 修改目标页SQL查询,同时使用两个参数
注意:直接将$_GET参数拼接进SQL语句存在严重SQL注入风险,必须使用预处理语句保证安全,以下是标准实现方式:
// 先校验必要参数是否存在 if(isset($_GET['Sec_No']) && isset($_GET['Sec_Sub'])){ $secNo = $_GET['Sec_No']; $secSub = $_GET['Sec_Sub']; // 编写带占位符的SQL语句 $sql = "SELECT theo_stu_sections.Sec_No, theo_stu_sections.St_No, students.Name, theo_stu_sections.Mid FROM students INNER JOIN theo_stu_sections ON students.St_ID = theo_stu_sections.St_No WHERE Sec_No = ? AND Sec_Sub = ? ORDER BY students.Name"; // 初始化预处理语句 $stmt = mysqli_prepare($conn, $sql); // 绑定参数("ss"表示两个字符串类型参数,若字段为整数可改为"ii") mysqli_stmt_bind_param($stmt, "ss", $secNo, $secSub); // 执行查询 mysqli_stmt_execute($stmt); // 获取结果集 $result = mysqli_stmt_get_result($stmt); // 后续可循环处理$result中的数据... } else { // 参数缺失时的提示逻辑 echo "缺少必要的查询参数"; }
若因特殊场景需使用字符串拼接(不推荐),必须对参数进行转义处理:
if(isset($_GET['Sec_No']) && isset($_GET['Sec_Sub'])){ $secNo = mysqli_real_escape_string($conn, $_GET['Sec_No']); $secSub = mysqli_real_escape_string($conn, $_GET['Sec_Sub']); $sql = "SELECT theo_stu_sections.Sec_No, theo_stu_sections.St_No, students.Name, theo_stu_sections.Mid FROM students INNER JOIN theo_stu_sections ON students.St_ID = theo_stu_sections.St_No WHERE Sec_No='".$secNo."' AND Sec_Sub='".$secSub."' ORDER BY students.Name"; $result = mysqli_query($conn, $sql); }
内容的提问来源于stack exchange,提问作者sami
相关产品推荐
相关产品推荐

