简体   繁体   English

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

[英]How to delete data based on value in session variable

add.php(When user click add photo) 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 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 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']); 
}

To use session variables, please add session_start() at the begin of your files, otherwise they aren't used. 要使用会话变量,请在文件开头添加session_start(),否则将不使用它们。 Secondly you are adding an array into a next array. 其次,您要将一个数组添加到下一个数组中。 so you have to use $_SESSION["auctionImages"] = $auctionImage; 因此您必须使用$_SESSION["auctionImages"] = $auctionImage; or 要么

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

Further debugging can be done by print_r($_SESSION); 进一步的调试可以通过print_r($ _ SESSION)完成。 so you can track the contents of this array 这样您就可以跟踪该数组的内容

You have a problem here 你这里有问题

$_SESSION["auctionImages"][]= $auctionImage;

Variable $auctionImage itself an array so need not to assign as an array again in SESSION variable. 变量$auctionImage本身是一个数组,因此不必在SESSION变量中再次指定为数组。 Make it as 做为

$_SESSION["auctionImages"]= $auctionImage;

It works fine for me. 这对我来说可以。

below is the code I worked. 下面是我工作的代码。

<?php
//$filename  = $_FILES["file"]["name"];

 $auctionImage = array(); 

 $auctionImage = array('IMG_2923.JPG', 'IMG_2924.JPG', 'IMG_2925.JPG');  // assigning sample variables  // will be IMG_2923.JPG, IMG_2924.JPG and etc

 $_SESSION["auctionImages"]= $auctionImage; // Removed '[]' from your coding

 $a = 'IMG_2923.JPG'; // Assigning for testing purpose
 $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']); // Printing final session value. It prints without the key image name



?>

The Problem -- What you should do: 问题-您应该做什么:

You basically have to populate the SESSION variable like this: 基本上,您必须像这样填充SESSION variable

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

You're meant to address each element therefore, like this: 因此,您必须处理每个元素,如下所示:

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

$n is the numbered index value for a particular element in the array. $n是数组中特定元素的编号索引值。 Therefore, if $n is 0, the array would return "IMG_29.29.JPG" and if the $n is 1, the array would return "IMG_2924.JPG". 因此,如果$n为0,则数组将返回“ IMG_29.29.JPG”,如果$n为1,则数组将返回“ IMG_2924.JPG”。

However, you are populating the array like this: 但是,您正在像这样填充数组:

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

If you dump this array, it will give you: 如果转储此数组,它将为您提供:

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

Which is not the behaviour you require. 这不是您要求的行为。

Solution

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

This is more shorter, cleaner and neater. 这样更短,更清洁,更整洁。

Also, you can use the alternative array syntax which is [ and ] . 另外,您可以使用替代数组语法[] So, you can declare arrays using $var = []; 因此,您可以使用$var = [];声明数组$var = []; which is shorter than $var = array(); $var = array();要短 .

Firstly, the variable $a is the text to be searched in the array. 首先,变量$a是要在数组中搜索的文本。

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

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

This is the second part of the code. 这是代码的第二部分。 This is all you need to have. 这就是您所需要的。

Also, make sure you have started the session by invoking session_start() in the top of the file if you haven't done yet. 另外,如果尚未启动会话,请通过调用文件顶部的session_start()来确保已启动会话。

A few comments 一些评论

  • Consider taking a look at the Unofficial PHP standards here . 考虑在此处查看非官方的PHP标准 It would be better if you name your variables in $camelCase . 如果将变量命名为$camelCase会更好。 Therefore, it would be better to rename $filename to $fileName . 因此,最好将$filename重命名为$fileName
  • Also good job on using strict comparison which is !== . 使用strict comparison !==也很不错。
  • Also, use more meaningful variable names. 另外,使用更有意义的变量名。 $a does not make sense. $a没有意义。 Something like $searchString would be really meaningful and the code will self-document your code. 诸如$searchString类的东西确实很有意义,并且代码将自我记录您的代码。

Links 链接

is_array - Returns TRUE if the passed identifier is an array, otherwise returns FALSE. is_array如果传递的标识符是数组,则返回TRUE,否则返回FALSE。


Let's now solve the problem with the full code you have given me. 现在,用您提供给我的完整代码解决问题。 Let's start with delete.php : 让我们从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']); 
}

Now, let's fix your UploadImages.php file: 现在,让我们修复您的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;
        }

    }                                               
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM