Hi I have a php code that uploads a file to mysql db then I detrmine the id of the last inserted file and download the file .e user is asked if he wants to save the file and then asked for te file name.
I want te php to automatically save the file and overrides the previous downloaded file.
Any advise will be apprecited.
If 1stfile upload = name.txt and 2ndfile upload=surname.txt.Surname.txt must overwrite name.txt.
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli("127.0.0.1","root","blabla",'blabla');//143.160.11.51
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "INSERT INTO file (`name`,`mime`,`size`,`data`,`created`)
VALUES ('{$name}', '{$mime}', '{$size}', '{$data}', NOW())";
// Execute the query
$resulta = $dbLink->query($query);
$getid="SELECT id FROM file ORDER BY created DESC LIMIT 1 ";
$result2 = $dbLink->query($getid);
$mysqli->error;
$row1=$result2->fetch_assoc();
// Close the mysql connection
$dbLink->close();
}}
else
{echo 'Error! A file was not sent!';}
/////////////////////////Download///////////////////////////////////////////
// Make sure an ID was passed
// Get the ID
$id= $row1['id'];
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli("127.0.0.1","root","blabla",'blabla');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "SELECT `mime`, `name`, `size`, `data`
FROM `file`
WHERE `id` = {$id}";
$resultb=$dbLink->query($query);
if($resultb) {
// Make sure the result is valid
if($resultb->num_rows == 1) {
$rowb =mysqli_fetch_assoc($resultb);
// Print headers
header("Content-Type: ".$rowb['mime']);
header("Content-Length: ".$rowb['size']);
header("Content-Disposition: attachment; filename=".$rowb['name']);
// Print data
echo $rowb['data'];
}
else {
echo 'Error! No image exists with that ID.';
}
// Free the mysqli resources
@mysqli_free_result($resultb);
}
else { echo "Error! Query failed: <pre>{$dbLink->error}</pre>"; }
@mysqli_close($dbLink);
}
echo 'end';
echo $rowb['data'];
?>