沃梦达 / 编程问答 / php问题 / 正文

如何根据会话变量中的值删除数据

How to delete data based on value in session variable(如何根据会话变量中的值删除数据)

本文介绍了如何根据会话变量中的值删除数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

add.php(当用户单击添加照片时)

  <div class="col-lg-12">
        <div class="form-group" id="image">
             <label>Auction Image</label>
<div action="uploadImages.php" class="dropzone" id="uploadImageForm"></div>
 <span class="help-block" id="image-error"></span>
        </div>
</div>

<script>
$(function () {
        Dropzone.options.uploadImageForm = false;
        Dropzone.options.uploadImageForm = {
          paramName: "file",
          maxFilesize: 1,
          acceptedFiles: 'image/*',
          maxFiles: 5,
          dictDefaultMessage: '<img src="images/icon_images.svg" width="100"/><br/><br/>Drop auction image here',
          addRemoveLinks: true,
removedfile: function(file) {
    var name = file.name;        
    $.ajax({
        type: 'POST',
        url: 'delete.php',
        data: "id="+name,
        dataType: 'html'
    });
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;        
              }
        };
</script>

UploadImages.php

<?php
session_start();
require 'config/database.php';

if (!isset($_SESSION['user'])) {
    exit;
}
else if (!empty($_FILES)) {

    $auctionImage = array();
    $size = getimagesize($_FILES['file']['tmp_name']);

    if (!$size) {
        header('Content-type: text/json');
        header('Content-type: application/json');
        echo json_encode(['error']);
        exit;
    }
    else {
        $n = 0;
        $tempFile = $_FILES['file']['tmp_name'];
        $imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $targetPath = dirname( __FILE__ ) . '/images/uploads/';
        $targetFile =  $targetPath . $imageName;

        $filename  = $_FILES["file"]["name"];

        move_uploaded_file($tempFile,$targetFile);

        // isset id = insert gallery image into database
        if (isset($_GET['id'])) {
            $stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
            $stmt->bindParam(':uid', $_SESSION['user']['id']);
            $stmt->bindParam(':id', $_GET['id']);
            $stmt->bindParam(':url', $imageName);
            $stmt->execute();
        }
        else {
            $auctionImage[] = $filename;
        }

    }                                               

    if (!empty($auctionImage)) {
        // record uploaded image name, will store into session
        // store uploaded image into session
        //$_SESSION["auctionImages"] = array();
        $_SESSION["auctionImages"][] = $auctionImage;
    }


}

delete.php

<?php
$targetPath = dirname( __FILE__ ) . '/images/uploads/';

unlink($targetPath.$_POST['id']);

session_start();
$a = $_POST['id']; 
$key=array_search($a,$_SESSION['auctionImages']);


 if($key!==false){
  unset($_SESSION['auctionImages'][$key]);
  $_SESSION["auctionImages"] = array_values($_SESSION["auctionImages"]);

 echo '<pre>'; print_r($_SESSION['auctionImages']); 
}

推荐答案

问题--您应该做什么:

您基本上必须像这样填充SESSION variable

$_SESSION["auctionImages"] = array(
    "IMG_2923.JPG", "IMG_2924.JPG"
);

因此,您应该处理每个元素,如下所示:

$_SESSION["auctionImages"][$n];

$n是数组中特定元素的编号索引值。因此,如果$n为0,则数组将返回"img_29.29.JPG";如果$n为1,则数组将返回"img_2924.JPG"。

但是,您按如下方式填充数组:

$_SESSION["auctionImages"][] = array(
    "IMG_2923.JPG", "IMG_2924.JPG"
);

如果转储此数组,它将为您提供:

array(
    array(
        "IMG_2923.JPG", "IMG_2924.JPG"
    )
);

这不是您要求的行为。

解决方案

$filename  = $_FILES["file"]["name"];
if(!is_array($_SESSION["auctionImages"])) {
    $_SESSION["auctionImages"] = [];
}
$_SESSION["auctionImages"][] = $filename;

这个更短、更干净、更整洁。

此外,您还可以使用[]替代数组语法。因此,您可以使用比$var = array();更短的$var = [];来声明数组。

首先,变量$a是要在数组中搜索的文本。

$key = array_search($a, $_SESSION["auctionImages"]);

if ($key !== false) {
    unset($_SESSION["auctionImages"][$key]);
}

这是代码的第二部分。这就是您需要的全部。

此外,如果尚未启动会话,请确保已通过调用文件顶部的session_start()启动会话。

几点意见

  • 考虑看看Unofficial PHP standards here。如果在$camelCase中命名变量会更好。因此,最好将$filename重命名为$fileName
  • 使用strict comparison也不错,!==
  • 另外,使用更有意义的变量名称。$a没有意义。像$searchString这样的代码将非常有意义,并且代码将自我记录您的代码。

链接

is_array-如果传递的标识符是数组,则返回True,否则返回False。


现在让我们用您给我的完整代码来解决这个问题。让我们从delete.php开始:

<?php
session_start();

$targetPath = dirname( __FILE__ ) . '/images/uploads/';

if(!isset($_POST['id'])) {
    echo "ID has not been defined!";
    exit;
}

$id = $_POST['id'];

unlink($targetPath . $id);

$key = array_search($id, $_SESSION['auctionImages']);

if ($key !== false) {
    unset($_SESSION['auctionImages'][$key]);
    echo '<pre>'; 
    print_r($_SESSION['auctionImages']); 
}

现在,让我们修复您的UploadImages.php文件:

<?php
session_start();
require 'config/database.php';

if (!isset($_SESSION['user'])) {
    exit;
}
if (!empty($_FILES)) {

    if(!isset($_SESSION["auctionImages"]) && !is_array($_SESSION["auctionImages"])) {
        $_SESSION["auctionImages"] = [];
    }

    $size = getimagesize($_FILES['file']['tmp_name']);

    if (!$size) {
        header('Content-type: text/json');
        header('Content-type: application/json');
        echo json_encode(['error']);
        exit;
    }
    else {
        $tempFile = $_FILES['file']['tmp_name'];
        $imageName = uniqid() . '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $targetPath = dirname( __FILE__ ) . '/images/uploads/';
        $targetFile =  $targetPath . $imageName;

        $fileName  = $_FILES["file"]["name"];

        move_uploaded_file($tempFile, $targetFile);

        // isset id = insert gallery image into database
        if (isset($_GET['id'])) {
            $stmt = $db->prepare("INSERT INTO image (user_id, related_id, related_type, url) VALUES (:uid, :id, 'gallery', :url)");
            $stmt->bindParam(':uid', $_SESSION['user']['id']);
            $stmt->bindParam(':id', $_GET['id']);
            $stmt->bindParam(':url', $imageName);
            $stmt->execute();
        }
        else {
            $_SESSION["auctionImages"][] = $fileName;
        }

    }                                               
}

这篇关于如何根据会话变量中的值删除数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何根据会话变量中的值删除数据

基础教程推荐