在PHP页面上获取SQL ID并将其传递给另一个PHP页面

问题描述 投票:1回答:1

有谁可以帮我从SQL获取ID变量并将其发送到另一个PHP页面? index.php输出:(Image1)enter image description here

checks.php输出:(Image2)enter image description here

我需要做的是以下内容:每当我点击index.php页面状态字段下的“OK”或“NOK”时,我需要它带我到另一个名为checks.php的PHP页面并向我显示我点击的行的ID

所以例如,在Image1(这是index.php页面)上,如果我点击状态列下的确定有ID=2,我想把这个ID变成变量并将它传递到下一页checks.php只显示有ID=2的行并非所有ID都在桌子内。

这是我的index.php代码

<?php
    require_once('connection.php');
    $result = $conn->prepare("SELECT * FROM report");
    $result->execute();
    for($i=0; $row = $result->fetch(); $i++){
?>
    <tr>
        <td><label><?php echo $row['ID']; ?></label></td>
        <td><label><?php echo $row['ElapsedTime']; ?></label></td>
        <td><label><?php echo $row['Computer']; ?></label></td>
        <td><label><?php echo $row['Manufacturer']; ?></label></td>
        <td><label><?php echo $row['ModelName']; ?></label></td>
        <td><label><?php echo $row['UserType']; ?></label></td>
        <td><label><?php echo $row['UserName']; ?></label></td>
        <td><label><a href='checks.php?id=". urlencode($row['ID']) ."'><?php echo $row['Status']; ?></a></label></td>
    </tr>
    <?php } ?>

这是我的checks.php代码

<?php
    require_once('connection.php');
    $id = $_GET['id'];
    $result = $conn->prepare("SELECT * FROM checks,report where checks.ID = report.ID and checks.ID = $id");
    $result->execute();
    for($i=0; $row = $result->fetch(); $i++){
?>
    <tr>
        <td><label><?php echo $row['ID']; ?></label></td>
        <td><label><?php echo $row['WiFi']; ?></label></td>
        <td><label><?php echo $row['Printers']; ?></label></td>
        <td><label><?php echo $row['Notepad']; ?></label></td>
    </tr>
    <?php } ?>

如果我手动设置ID,如http://localhost/checks.php?id=2,它工作正常

php mysql
1个回答
1
投票

您的问题出在HTML代码的最后一行td

<td><label><a href='checks.php?id=". urlencode($row['ID']) ."'><?php echo $row['Status']; ?></a></label></td>

如您所见,您手动设置href标记的a并尝试将PHP变量$row['ID']添加到其中。然而,在此之前,您已经关闭了PHP上下文几行,因此您处于HTML上下文中,您无法访问PHP变量。

解决方案是再次打开PHP标记,就像之后使用$row['Status']一样。你也不需要使用urlencode,因为ID是数字的,所以它不会被转换。

<td><label><a href='checks.php?id=<?= $row['ID'] ?>'><?= $row['Status'] ?></a></label></td>

我也使用短标签<?= ... ?>而不是<?php echo '...' ?>

© www.soinside.com 2019 - 2024. All rights reserved.