通过检索id PHP foreach来删除mysql行

时间:2018-05-12 20:05:10

标签: php mysql pdo

我已经创建了一个foreach语句,回应了所有已注册用户的内容,如何创建一个从该行删除该用户的按钮?我试过这个:

$query = "
SELECT id
     , name
     , bname
     , email
     , address
     , agent
     , status
     , notes 
  FROM prospects
";

        try {
            $stmt = $db->prepare($query);
            $stmt ->execute();
        }
        catch(PDOException $ex) {
            die("Failed to run query. Tell the website owner!");
        }
        $rows = $stmt->fetchAll();
        foreach($rows as $row) {
            echo "<tbody>
            <th>".$row['name']."</th>";
            echo "BLAH BLAH BLAH!";
            echo "<form method='post'><th><button type='submit' name='delete' class='btn btn-white btn-round btn-just-icon'>
                <i class='material-icons'>remove_circle_outline</i>
                <div class='ripple-container'></div>
            </button></th></tbody></form>";
        } $id = $db->prepare("SELECT id FROM example");
        $id->execute();

        $result = $id->fetch(PDO::FETCH_ASSOC);

        if(isset($_POST['delete'])) {
                try {
                    $sql = "DELETE FROM example WHERE id='".$result."'";
                    $db->exec($sql);
                }
                catch(PDOException $e) {
                    echo $sql . "<br />". $e->getMessage();
                }
            }

它返回此错误:

  

注意:数组到字符串转换....

我知道这是因为我抓住了id并且我从数据库中抓取了一系列ID?那么当我点击按钮时如何删除特定的行?

1 个答案:

答案 0 :(得分:0)

您必须指定数组中的哪个元素包含id值。

<强>尝试:

$sql = "DELETE FROM example WHERE id='".$result['id']."'";