duanhao4156 2018-05-12 20:05
浏览 83
已采纳

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

I've created a foreach statement that echos out some stuff about all users registered, how do I make a button that deletes that user from the row? I've tried this:

$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();
                }
            }

It returns this error:

Notice: Array to string conversion....

I know this is because I've grabbed the id and there is an array of ids that I've grabbed from the database? So how do I do delete a specific row when i click on the button?

  • 写回答

1条回答 默认 最新

  • douyan1970 2018-05-13 00:09
    关注

    You have to specify which element in array holds the id value.

    Try:

    $sql = "DELETE FROM example WHERE id='".$result['id']."'";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀