如何获取表格中某行的特定ID并使用该ID更新

时间:2019-03-10 16:03:11

标签: php mysql

所以我想在表的末尾添加一个按钮,一旦单击它,它将把数据库中的“ baatinn”从0更新为1。我想出了如何添加按钮等,但是当我单击时它将更新所有行,而不是您单击按钮的行从0更新到1。因此,我需要知道的是,它仅更新您单击按钮的行的“ baatinn”。我有一个ID的主键。并且“ baatinn”的默认值为0

Database

HTML:

<tr>
  <th>Båt ut</th>
  <th>Båt inn</th>
  <th>Båtnr</th>
  <th>Fornavn</th>
  <th>Etternavn</th>
  <th>Tid</th>
  <th>Kr</th>
  <th>Edit</th>
</tr>

PHP:

$sql = "SELECT utleid, inntid, baatnr, fornavn, etternavn, tid, kr, baatinn     FROM utleie WHERE baatnr LIKE '%$sok%' or fornavn LIKE '%$sok%' or etternavn     LIKE '%$sok%' or tid LIKE '%$sok%' ORDER BY id desc";
$result = $conn-> query($sql);

if ($result-> num_rows > 0) {
    while ($row = $result-> fetch_assoc()) {
        ?>
        <tr>
            <td><?php echo $row["utleid"]; ?></td>
            <td><?php echo $row["inntid"]; ?></td>
            <td><?php echo $row["baatnr"]; ?></td>
            <td><?php echo $row["fornavn"]; ?></td>
            <td><?php echo $row["etternavn"]; ?></td>
            <td><?php echo $row["tid"]; ?></td>
            <td><?php echo $row["kr"]; ?></td>
            <td><form method="post" action="innlevering.php">
        <button name="edit" value="1">Edit</button>
</form></td>
        </tr>
        <?php 
    }
    echo "</table>";
} else {
    echo "0 results";

Innlevering.php

<?php
include_once 'dbconnect.php';

$id = $_POST['id'];

if ($_POST['edit']) {
   $conn->query("UPDATE utleie SET baatinn=1 WHERE id={$id}");
}


?>

2 个答案:

答案 0 :(得分:1)

您可以编辑生成表的php代码。您必须将按钮的名称设置为id并将值设置为数据库表的id字段(因此,您还必须按如下所示编辑mysql查询

PHP

$sql = "SELECT id, utleid, inntid, baatnr, fornavn, etternavn, tid, kr, baatinn     FROM utleie WHERE baatnr LIKE '%$sok%' or fornavn LIKE '%$sok%' or etternavn     LIKE '%$sok%' or tid LIKE '%$sok%' ORDER BY id desc";
$result = $conn-> query($sql);

if ($result-> num_rows > 0) {
    while ($row = $result-> fetch_assoc()) {
        ?>
        <tr>
            <td><?php echo $row["utleid"]; ?></td>
            <td><?php echo $row["inntid"]; ?></td>
            <td><?php echo $row["baatnr"]; ?></td>
            <td><?php echo $row["fornavn"]; ?></td>
            <td><?php echo $row["etternavn"]; ?></td>
            <td><?php echo $row["tid"]; ?></td>
            <td><?php echo $row["kr"]; ?></td>
            <td><form method="post" action="innlevering.php">
        <button name="id" value="<?php echo $row["id"]; ?>">Edit</button>
</form></td>
        </tr>
        <?php 
    }
    echo "</table>";
} else {
    echo "0 results";

答案 1 :(得分:0)

将所有行设置为一个表单元素,然后使用value =当前行主键的按钮。

<button name="id" value="<?php echo $row["primary_key_of_this_row"]; ?>">Edit</button>