簡體   English   中英

如何在php函數中刪除頁面中mySQL中的特定行

[英]How to delete a specific rows in mySQL in a page, within a php function

我對如何從頁面中的函數刪除數據庫中的特定行感到頭疼。 這就是我被困住的地方:我知道我必須使用一行中的特定ID,所以我把我的$ id放在一個while循環中,在這里我被卡住了。 因為我不知道如何從特定行檢索該ID。 但是在每行中都有一個“提交”按鈕來刪除它。 有人可以幫幫我嗎?

在我的另一頁中,當我調用這兩個函數時:

<?php 
session_start();
include_once('connect.php');
$object = new User;
if(isset($_POST['supprimer'])) {
    $object->supprimer($id);
}
?>

<html>
    <head>
    <link rel="stylesheet" type="text/css" href="public/css/layout.css">
    </head>
    <body>
        <?php $object->showConcessionnaire(); ?>
    </body>
</html>

PHP

public function showConcessionnaire(){
            $st = $this->db->prepare("SELECT * FROM `phplogin`.`users` WHERE type='Concessionnaire'");
            $st->execute();
            echo '<form action="supprConc.php" method="post">
            <table class="tableCredit">
                <tr class="">
                    <th>Date</th>
                    <th>Nom d\'utilisateur</th>
                    <th>Mot de pass</th>
                    <th>E-mail</th>
                    <th>Cr&eacute;&eacute; par</th>
                    <th></th>
                    <th></th>
                </tr>
                ';
            while($r = $st->fetch(PDO::FETCH_ASSOC)){
                $id = $r['ID'];
                echo '<tr class="lightGray">
                    <td>'.$r['Date'].'</td>
                    <td>'.$r['username'].'</td>
                    <td>'.$r['password'].'</td>
                    <td>'.$r['E-mail'].'</td>
                    <td>'.$r['Creer par'].'</td>
                    <td></td>
                    <td><input type="submit" name="supprimer" value="X" class="logout"></td>
                    </tr>';
            }
            echo '</table></form>';
        }


    public function supprimer($id){
            $st = $this->db->prepare("DELETE FROM `phplogin`.`users` WHERE `users`.`id` = '$id'");
            $st->execute();
        }

一種解決方案是插入包含行ID的隱藏輸入。

<input type="hidden" name="rowID" value="$id" />

然后在調用你的函數時......

$object->supprimer($_POST['rowID']);

確保轉義字符串以避免SQL注入!

改變這個:

<td><input type="submit" name="supprimer" value="X" class="logout"></td>

對此:

<td><input type="submit" name="supprimer" value=".$id." class="logout"></td>

然后將您的函數調用更改為:

$object = new User;
if(isset($_POST['supprimer'])) {
    $id = $_POST['supprimer'];
    $object->supprimer($id);
}

這不是完全安全的解決方案,而更像是證明該方法的概念證明。

您可以使用您的ID添加隱藏的輸入字段:

<input type="hidden" name="id" value="'.$id.'">

當然這是你的echo ,你應該將表格移動到你的<td>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM