删除确认仅使用PHP


Delete confirm only using PHP

我想删除链接以删除SQL数据库上的图像。我的任务是创建一个删除确认选项,不使用JavaScript,只使用PHP。

require_once("photoalbum-common.php");
$pdo = connect();
if ( isset( $_GET['deletionid'])) {
  $errorMessage = deletePhotograph( $pdo, $_GET['deletionid']);
  if ( $errorMessage != "") {
    print "<div class='errormessage'>$errorMessage</div>'n";
  } else {
    print "<div class='message'>Image deleted.</div>'n";    
  }
}

下面的代码在"photoalbum-common.php"中。

<?php
function deletePhotograph( $pdo, $deletionid) {
  $errorMessage = "";
  // retrieve name of image file so we can delete it
  $stmt = $pdo->prepare("SELECT `image` FROM `photographs` WHERE `photoid`=?");
  $stmt->execute( array( $deletionid));  
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  if ( count( $rows) == 1) {
    // delete file
    unlink( "images/".$rows[0]['image']);    
    // delete database record
    $stmt = $pdo->prepare("DELETE FROM `photographs` WHERE `photoid`=?");
    $stmt->execute( array( $deletionid));  
    $affected_rows = $stmt->rowCount();    
  } else if (count( $rows) > 1) {
    $errorMessage .= "ID matches more than one record. ";
  } else {
    $errorMessage .= "ID not found: nothing to delete. ";
  }
  return $errorMessage;
}
?>

使用类似的方法。一个间隙页面,接受GET请求:

获取请求GET /delete.php?id=123

你确定要删除吗?

POST请求POST /delete.php?id=123

执行PDO。

您应该为PHP编写代码。如果答案还不够,那么,我们开始吧:

<?php
  if (count($_POST)) {
    // POST Request
    deletePhotograph();
  } else {
    // GET Request
    ?>
    <p>Are you sure you wanna delete?</p>
    <!-- Empty action will POST to the same page. -->
    <form action="" method="POST"><input type="submit" value="I confirm, Delete" /></form>
    <?php
  }
?>