【问题标题】:Undefined Array Key on php [duplicate]php上未定义的数组键[重复]
【发布时间】:2022-12-04 09:51:23
【问题描述】:

我得到一个错误 undefined array key for 'id_post',我使用这个 href 删除方法

<?php

require 'koneksi.php';
$blogs = new blog();

$no = 1;
        foreach ($blogs->show() as $b) {
?>


<button type="button"><a href="proses.php?aksi=hapus&id=<?= $b['id_post'] ?>">Hapus</a></button>

<?php }; ?>

这里是 proses.php 文件

<?php

include 'koneksi.php';
$blog = new blog();
$kat = new kat();

$aksi = $_GET['aksi'];

if ($aksi == "hapus") {
    $blog->hapus($_GET['id_post']);
}

这里的功能

public function hapus($id_post)
    {
        $connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
        mysqli_query($connect, "DELETE FROM blog WHERE id_post='$id_post'");
    }

我试过在功能上使用类似的东西但仍然没有任何改变

public function hapus($id_post)
    {
        $connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
        if (isset($_GET['id_post'])) {
            $id = $_GET[$id_post];
            mysqli_query($connect, "DELETE FROM blog WHERE id_post='$id'");
        }
    }

我以前尝试过相同的代码并且可以正常工作,但现在出现了一些错误。请给我一些启示

【问题讨论】:

  • 你的查询参数是id,不是id_post

标签: php arrays


【解决方案1】:

您收到的错误是因为您试图访问 $_GET 数组中的 id_post 键,但它不存在。这是因为您在 HTML 中将 id 参数作为 id= 传递,但您试图在 PHP 代码中将其作为 $_GET['id_post'] 访问。

要解决此问题,您可以将 HTML 更改为使用 id_post 而不是 id,如下所示:

<button type="button"><a href="proses.php?aksi=hapus&id_post=<?= $b['id_post'] ?>">Hapus</a></button>

或者您可以更改 PHP 代码以使用 $_GET['id'] 而不是 $_GET['id_post'],如下所示:

public function hapus($id_post)
{
    $connect = mysqli_connect($this->host, $this->uname, $this->pw, $this->db);
    mysqli_query($connect, "DELETE FROM blog WHERE id_post='$_GET['id']'");
}

这两项更改都应该可以修复您看到的错误。如果您有任何其他问题,请告诉我。

【讨论】:

    猜你喜欢
    • 2022-11-20
    • 1970-01-01
    • 2021-07-01
    • 2019-10-22
    • 2016-04-06
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多