add.php(When user click add photo)
-
The Problem -- What you should do:
You basically have to populate the SESSION variable
like this:
$_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. 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".
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 = [];
which is shorter than $var = array();
.
Firstly, the variable $a
is the text to be searched in the array.
$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.
A few comments
- Consider taking a look at the Unofficial PHP standards here. It would be better if you name your variables in
$camelCase
. Therefore, it would be better to rename $filename
to $fileName
.
- Also good job on using
strict comparison
which is !==
.
- Also, use more meaningful variable names.
$a
does not make sense. Something like $searchString
would be really meaningful and the code will self-document your code.
Links
is_array - Returns TRUE if the passed identifier is an array, otherwise returns FALSE.
Let's now solve the problem with the full code you have given me. Let's start with delete.php
:
';
print_r($_SESSION['auctionImages']);
}
Now, let's fix your UploadImages.php
file:
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;
}
}
}