2017-03-31 74 views
-1

在同一頁面中,我有一個表單,要求用戶確認是否要刪除數據,並且我有PHP代碼。現在,我想使用superglobals從數據庫中刪除一行,但我無法弄清楚這個問題。它總是回聲「不刪除」。另外如果用戶選擇不刪除,我想執行重定向到home.php從同一頁中的表單中刪除表格中的行

<body> 

<h2>Are you sure you want to delete the student?</h2> 
<form method="post" action="<?=$_SERVER['PHP_SELF']?>"> 
    <input type="submit" name="submit" value="YES" /> 
    <input type="submit" name="submit" value="NO" /> 
</form> 

<?php 

$fields = array('id', 'student', 'firstname', 'lastname', 'email'); 
$student= array(); 

foreach ($fields as $field) { 
$student[$field]=""; 
} 

if(isset($_POST['id'])) { 
    $id = htmlspecialchars($_POST['id']); 
} 
else if(isset($_GET['id'])) { 
    $id = htmlspecialchars($_GET['id']); 
} 

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    if(!empty($id)) { 

    include "inc_DBConnect.php"; 

    $SQLString = "DELETE FROM students WHERE id = '$id'"; 

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString); 
    if($SQLQueryResult === FALSE) { 
     echo "<p>There was an error retrieving the record.<br />\n</p>"; 
    } else { 
     echo "<p>Student deleted</p>"; 
    } 
} else { 
    echo "NOT DELETED"; 
} 


} 

?> 
</body> 
+0

很可能是因爲您沒有執行POST請求。不知道是什麼阻止你使用'var_dump()'或'print_r()'並且首先檢查你自己而不是在這裏詳細說明。 –

+0

做$ _SERVER打印[「REQUEST_METHOD」];還有變量ID從哪裏來?因爲我無法在你的表格上看到它。我認爲這應該是一個隱藏的領域或什麼 – Akintunde007

+0

你的表單顯示沒有「id」(var或輸入),你試圖在之後重用...在哪裏$ _POST ['id']或$ _GET [' ID']來自? – OldPadawan

回答

0

嘗試,如果

OR var_dump($_SERVER)和檢查什麼是錯的本陣之前打印$_SERVER['REQUEST_METHOD']變量 - 也許您的服務器沒有設置REQUEST_METHOD關鍵。

通過其他的方法你也應該嘗試這種方式

if(count($_POST)){/*....*/}; 
0

在你的代碼沒有id字段有那麼將不會得到它POST請求。

<body> 
<?php 
// check this too when your form is submitting 
// print_r($_SERVER); 
?> 
<h2>Are you sure you want to delete the student?</h2> 
<form method="post" action="<?=$_SERVER['PHP_SELF']?>"> 
    <input type="hidden" name="id" value="<?php echo $_GET['id']?>" /> 
    <input type="submit" name="submit" value="YES" /> 
    <input type="submit" name="submit" value="NO" /> 
</form> 

<?php 

$fields = array('id', 'student', 'firstname', 'lastname', 'email'); 
$student= array(); 

foreach ($fields as $field) { 
$student[$field]=""; 
} 

if(isset($_POST['id'])) { 
    $id = htmlspecialchars($_POST['id']); 
} 
else if(isset($_GET['id'])) { 
    $id = htmlspecialchars($_GET['id']); 
} 

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    if(!empty($id)) { 

    include "inc_DBConnect.php"; 

    $SQLString = "DELETE FROM students WHERE id = '$id'"; 

    $SQLQueryResult = mysqli_query($DBConnection, $SQLString); 
    if($SQLQueryResult === FALSE) { 
     echo "<p>There was an error retrieving the record.<br />\n</p>"; 
    } 
    else { 
     echo "<p>Student deleted</p>"; 
    } 
} 
else { 
    echo "NOT DELETED"; 
} 
} 

?> 
</body> 
+0

問題是,此代碼沒有超出服務器請求方法行。首先要了解的是該行返回的內容。它是一個POST,GET等 – Akintunde007