A part of my PHP code is only deleting the first one "post" on SQL instead of the selected one:

if (isset ($_POST['delete'])){
        $result = mysql_query ("SELECT * FROM posts") or die(mysql_error());
        $data = mysql_fetch_array($result);
        mysql_query ("DELETE FROM posts WHERE id = $data[id]");
        header("Location: main.php");
    };

Why is this happening?

有帮助吗?

解决方案

step by step, this is what you are doing aka why this is happening:

1) check if post variable delete is set:

if (isset ($_POST['delete'])){

2) fetch all posts from database:

$result = mysql_query ("SELECT * FROM posts") or die(mysql_error());

3) fetch the first item out of the $result array

$data = mysql_fetch_array($result);

4) delete the item we just fetched

mysql_query ("DELETE FROM posts WHERE id = $data[id]");

5) redirect to main.php

header("Location: main.php");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top