I have a download button on a form that updates a MySQL database, and updates the number of downloads/the download count of a file. I thought I’d be able to add the download
attribute to this form button and provide the url to the file so the file would also download. It seems you can only use the download
attribute on anchor <a>
links. That in itself isn’t an issue, I can just style the anchor link like I have the button – but how can I get it so when someone clicks the <a>
link, as well as downloading the image, it also submits data to the database?
Simplified version of form button that submits to MySQL database:
<form method="post">
<button type="submit" name="download">Download</button>
<input type="hidden" name="filename" value="<?php echo $image_filename; ?>">
</form>
A ‘download’ file link:
<a download href="localhost/project/image/file.jpg">Download</a>
I’ve also included the PHP function that updates the database for reference purposes. This function is called on the page itself where the images are downloaded. Note: $connection
is the database connection code that is imported at the top of the functions.php file where this function is.
PHP
function downloadCounter($connection, $filename) {
if (isset($_POST['download'])) {
// value from a hidden form element which outputs the filename
$filename = $_POST['filename'];
try {
$sql = "UPDATE lj_imageposts SET downloads = downloads +1 WHERE filename = :filename";
$stmt = $connection->prepare($sql);
$stmt->execute([
':filename' => $filename
]);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
}