I am facing problem deleting the correct files. I am displaying the list of files uploaded by the user sorted by the time of upload (last upload first). If there's a list of 3-4 files, no matter which file I click to delete, the first file in the list gets deleted, the file last uploaded that is. Here is my page displaying the files a particular user has uploaded.
<?php
$uid=$faculty_data['faculty_id']; //Assigns logged in id to a variable
$query="SELECT * FROM uploads ORDER BY datetime DESC"; //Sorts by date time
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
{
if($uid==$row['faculty_id']) //Checks if the logged in id matches with id in DB
{
echo '<form action="delete.php" method="POST">';
echo "<strong>File: </strong>";
$url=$row['link'];
$new="http://tofsis.com/fileshare/".$url;
echo "<a href='$new'>$new</a><br/>";
echo "<strong>On: </strong>".$row['datetime'];
echo '<br><input type="submit" name="delete" class="btn btn" value="Delete File"/>';
echo '<hr>';
echo '</form>';
}
}
?>
And this is my delete page:
<?php
$uid=$faculty_data['faculty_id'];
$query="SELECT * FROM uploads ORDER BY datetime DESC";
$result=mysql_query($query);
if(isset($_POST['delete']))
{
while($row=mysql_fetch_assoc($result))
{
if($uid==$row['faculty_id'])
{
$url=$row['link'];
$new="http://tofsis.com/fileshare/".$url;
$query="DELETE FROM uploads WHERE link = '$url'";
$result=mysql_query($query);
unlink($url);
}
}
header('Location: my_uploads.php');
exit();
}
else {
echo '<script type="text/javascript">alert("Oops something went wrong!")</script>';
header('Location: my_uploads.php');
exit();
}
?>
Can anyone please tell me where I am going wrong so that I can get my problem fixed?
A couple of changes should be make:
<?php
$uid=$faculty_data['faculty_id']; //Assigns logged in id to a variable
$query="SELECT * FROM uploads ORDER BY datetime DESC"; //Sorts by date time
$result=mysql_query($query);
while($row=mysql_fetch_assoc($result))
{
if($uid==$row['faculty_id']) //Checks if the logged in id matches with id in DB
{
$file_id = $row['id'];
echo '<form action="delete.php" method="POST">';
echo "<strong>File: </strong>";
$url=$row['link'];
$new="http://tofsis.com/fileshare/".$url;
echo "<a href='$new'>$new</a><br/>";
echo "<input type='hidden' value='$url' id='file_path' name='file_path' />";
echo "<input type='hidden' value='$file_id' id='id_file' name='id_file' />"; // new line
echo "<strong>On: </strong>".$row['datetime'];
echo '<br><input type="submit" name="delete" class="btn btn" value="Delete File"/>';
echo '<hr>';
echo '</form>';
}
}
?>
On the delete page, this:
<?php
$file_id=$_POST['id_file'];
$file_path = $_POST['file_path'];
$query="DELETE FROM uploads WHERE id = $file_id";
$result=mysql_query($query);
unlink($file_path); //this should works on deleting the file
?>
That should do the trick ;)
Add another hidden input that stores the File ID and Get it in your delete script and use it
You create a separate POST form for each available file but none of this forms contain any information about what file they refer to. I guess that $_POST contains nothing but a delete key with Delete File as value.
In your delete page, you read data from a variable that does not exist:
$uid=$faculty_data['faculty_id']
... and then you retrieve all files from the database to compare their ID against $uid. I guess you are removing all rows when the ID is zero.
To do:
Enable full error reporting. That's something you need to fix before you go further; it's impossible to code without the aid of error messages. Here's a brief explanation.
Add a hidden field to the form with the corresponding ID.
Read form data from $_POST, not from an arbitrary variable.
Learn some basic SQL, such as the WHERE clause, so you can do something like:
DELETE FROM uploads
WHERE faculty_id=333
Learn about SQL injection. Use a library that provides prepared statements.
Related
I am trying to pass on a row ID by user click on the specified row, onto another page. I have a table with ID and info column.
code below displays the wanted row ID and info
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[id] . $info[review] . <a href=edit.php?edit=$info[id]>edit</a></br> </br>" ; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
I want the user to be able to click on any of the rows and the selected row to pass on its ID onto another page. How do I do this?
This is the code on the other page and I want the ID on which the user clicked to replace "$info[id]" in the sql query. This replaces the whole column and not the specified row.
if(isset($_POST['id'])){
$update=$_POST['id'];
$db->exec("UPDATE infos SET info = '$update' WHERE reviewid = '$info[id]'");
}
In the edit page I have an input which the user can write to replace the selcted row (from the ID that gets passed on)
<form action="edit.php" method="POST">
<input type="text" name="id" value="">
<input type="submit" value=" Update "/>
</form>
So I want the ID that was passed from the first page to be used to replace the info row with the user input from the edit page
Pass the ID to the URL to the next page, navigate to the next page, then use $id =$_GET['id'];
Your edit=$info['id'] part is right but you're using $_POST and $_POST['id'], on the next page. The GET global is needed and it's named edit, not id
if ($info = $stmnt2->fetch()) {
echo '<p>Your Info:</p>';
do {
echo "$info[id] . $info[review] . <a href=edit.php?edit=$info[id]>edit</a></br> </br>" ; //The info id is contained in the $info['id']
} while ($info = $stmnt2->fetch());
} else {
echo "<p>No Info</p>";
}
edit.php:
if(isset($_GET['edit'])){
$update = $_GET['edit'];
$db->exec("UPDATE infos SET info = '$update' WHERE reviewid = '$info[id]'");
}
Also for future expansion and learning, read into how to do prepared statements with bound parameters if you are going to be using queries with variables built in. You're prone to sql injection currently and it's good practice to learn the newer and safer methods.
you can get the parameter value by using $_REQUEST
$update = $_REQUEST['edit'] in edit.php file
when you use $_REQUEST method you can catch both $_GET and $_POST values.
I am trying to build an upload component that saves the file information to a MySQL DB table. My first issue is that each time a user uploads a file, two entries are added to the database.
My next issue is that I was to grab an uploaded file and display it as a link for the user to click on to view in a new tab. Right now, the upload saves the file's server directory path. When I go to click on the file, I get an error message saying the directory path could not be found.
My biggest issue is the link problem to view the uploads. Then, if someone also has a suggestion for the double entry problem, that would also be appreciated.
My Code:
HTML: File upload feature - Successfully uploads all variables twice...
<form id="sgFileUpload" action='sg_addupload.php' target='hiddenFrame' method="POST" enctype="multipart/form-data">
<fieldset id='uploadBtnField'>
<input type="hidden" name="MAX_FILE_SIZE" value="50000000"/>
<input type='hidden' name='sgRef' id='sgRef' value='<?php echo $sgref ?>'>
<input type='file' name='searchFile' id='searchFile' multiple>
<input type='submit' name='startUpload' id='startUpload' value='Upload'>
</fieldset>
</form> <!-- End Form Input -->
My PHP: File upload to DB
if(isset($_POST['sgRef'])) {
$sgref=$_POST['sgRef'];
}
$fileName = $_FILES['searchFile']['name'];
$fSize = $_FILES['searchFile']['size'];
$fType = $_FILES['searchFile']['type'];
$target = "../bms/uploads/";
$fileTarget = $target.$fileName;
$tempFileName = $_FILES["searchFile"]["tmp_name"];
//$docType = $_POST['docType'];
$result = move_uploaded_file($tempFileName,$fileTarget);
if ($result) {
//run DB Connection code...
//Writes the information to the database
$sql="INSERT sg_uploads(sgref,file,type,size,content,doctype) VALUES('$sgref','$fileName','$fType','$fSize','$fileTarget','Other')";
$conn->query($sql);
if($conn->query($sql)) {
echo 'Your file <html><b><i>'.$fileName.'</i></b></html> has been successfully uploaded!';
} else {
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
//Free the result variables.
$sql->free();
$result->free();
//Close the Database connection.
$conn->close();
}//End If Statement.
PHP CODE: To display links from DB (PHP CODE FOR RETRIEVAL IS SUCCESSFUL)
<?php
while ($row = $result->fetch_array()) {
echo "<tbody>";
echo "<tr>";
echo "<td>" . "<a href=".$row['content']."' >".$row['file']."</a>". "</td>";
echo "<br/>";
echo "<br/>";
}//end while.
echo "</tr>";
echo "</tbody>";
$filename = $row[0];
echo "<p></p>";
?>
All help is appreciated! Thank you!
NOTE: the 'file' column in the database is a datatype of 'blob'.
"#Fred, yes it was a directory issue. Upon fixing this issue, I was able to successfully link the the page and view it. If you summarize your two suggestions as an answer, I will mark your response as the correct answer. Thank you!"
As I stated in comments:
The duplicate entries are caused by $conn->query($sql); if($conn->query($sql))
where there were two instances of query() being used.
You can just use the conditional statement and omit $conn->query($sql);.
For the path issue, this was also stated in comments that the folder's path wasn't properly indexed.
Footnotes:
You're presently open to an SQL injection. Best you use a prepared statement.
https://en.wikipedia.org/wiki/Prepared_statement
I'm creating a website where users will need to be able to upload images, and I'd like them to be able to delete those images. Right now, I have a page that will display all of the images that that user has uploaded, and I have a php set up to delete an image from the database. It just needs to be given the id of the image. I have it functioning with the GET method, but I'm concerned a user could find the URL for my delete php and put in random ids, deleting everyone's images. Is there a way I can adjust my code to make it safer?
<?php
$sql = "SELECT id, userid, name, image FROM images";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if ($imageUser == $row["userid"]){
echo "<tr>";
echo "<th>".$row["userid"]."</th>";
echo "<th>".$row["name"]."</th>";
echo "<th><img src='showimage.php?id=".$row["id"]."'></th>";
echo "<th><a href='imgdelete.php?id=".$row["id"]."'>delete</a></th>";
echo "</tr>";
}
}
} else {
echo "0 results";
}
?>
The delete.php simply deletes the entry WHERE id=$_GET['id'];
In a RESTful API, a GET request should never modify the data. If you want to delete items, you should use a POST or a DELETE request.
So I have a page with a postback form where users can delete records (which appear as checkboxes) from a database. When you click 'Submit', on the same page a confirmation message is displayed "Successfully deleted the record".
The problem is that the checkbox remains there. Only after you refresh the page, the checkbox disappears. How can I remove it right after the user clicks "Submit"?
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<?php
//Connect to the database
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query = "SELECT * FROM programmer";
$resultset = $conn->query($query);
while ($row = $resultset->fetch())
{
echo "<p class='col'>";
echo "<input type='checkbox' name='programmers[]' id='programmer".$row['programmer_id']."' value='".$row['programmer_id']."'>";
echo "<a href='' class='help tip-below' data-tip='".projects($row['programmer_id'])."'><label for='programmer".$row['programmer_id']."'> ".$row['programmer_name']." ".$row['programmer_surname']."</label></a>";
echo "</p>";
}?>
<input type="submit" value="Delete Programmer(s)" class="sub-del submit-btn">
</form>
<?php
if (isset($_POST['programmers'])){
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query="DELETE FROM programmer WHERE programmer_id=:programmer_id";
$query2="DELETE FROM project WHERE programmer_id=:programmer_id";
$query3="SELECT programmer_name, programmer_surname FROM programmer WHERE programmer_id=:programmer_id";
$pr_stmt=$conn->prepare($query);
$pr_stmt2=$conn->prepare($query2);
$pr_stmt3=$conn->prepare($query3);
$affected_rows=0;
$notWorking=false; // set this variable to check if a programmer is working or not on any project
$surnameDeletedProgs=array();
$nameDeletedProgs=array();
foreach($_POST['programmers'] as $programmer_id){
$pr_stmt->bindValue(':programmer_id',$programmer_id);
$pr_stmt2->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->execute();
//Get the names and surnames of the programmers who were deleted from the database and store them in arrays
$result=$pr_stmt3->fetch();
array_push($nameDeletedProgs,$result['programmer_name']);
array_push($surnameDeletedProgs,$result['programmer_surname']);
//Delete the programmer from the database
$affected_rows+=$pr_stmt->execute();
//If they were working on a project, delete the project also from the 'project' table
if(projects($programmer_id)!="Working on no projects at the moment"){
$pr_stmt2->execute();
echo "Also deleted the project they were working on";
}
else $notWorking=true;
}
//If they are not working on any project display this particular message
if ($notWorking){
echo "Hopefully, they were not working on any project at the moment so we just ";
}
//if there were no checkboxes selectes, display a message to tell people to select at least one programmer
if ($affected_rows==0){
echo "No programmers to delete. Please select at least one.";
exit;
}
//display how many programmers were deleted from the 'programmers' table and also what are their names
else{
echo "deleted ".$affected_rows." programmer(s)";
echo ". Successfully deleted:<ul>";
for($i=0;$i<count($nameDeletedProgs);$i++){
echo "<li>".$nameDeletedProgs[$i]." ".$surnameDeletedProgs[$i]."</li>";
}
echo "</ul>";
}
$conn=NULL;
}
Thanks a lot for your help!
Raluca
Currently, when you hit submit, you build the HTML output with the old data, then update the database. You need to first update the database and then get the data to build the UI. Your updated code should look like this:
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<?php
//Connect to the database
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
if (isset($_POST['programmers'])){
require_once("dboconn.php");
$conn=ConnectionFactory::connect();
$query="DELETE FROM programmer WHERE programmer_id=:programmer_id";
$query2="DELETE FROM project WHERE programmer_id=:programmer_id";
$query3="SELECT programmer_name, programmer_surname FROM programmer WHERE programmer_id=:programmer_id";
$pr_stmt=$conn->prepare($query);
$pr_stmt2=$conn->prepare($query2);
$pr_stmt3=$conn->prepare($query3);
$affected_rows=0;
$notWorking=false; // set this variable to check if a programmer is working or not on any project
$surnameDeletedProgs=array();
$nameDeletedProgs=array();
foreach($_POST['programmers'] as $programmer_id){
$pr_stmt->bindValue(':programmer_id',$programmer_id);
$pr_stmt2->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->bindValue(':programmer_id',$programmer_id);
$pr_stmt3->execute();
//Get the names and surnames of the programmers who were deleted from the database and store them in arrays
$result=$pr_stmt3->fetch();
array_push($nameDeletedProgs,$result['programmer_name']);
array_push($surnameDeletedProgs,$result['programmer_surname']);
//Delete the programmer from the database
$affected_rows+=$pr_stmt->execute();
//If they were working on a project, delete the project also from the 'project' table
if(projects($programmer_id)!="Working on no projects at the moment"){
$pr_stmt2->execute();
echo "Also deleted the project they were working on";
}
else $notWorking=true;
}
//If they are not working on any project display this particular message
if ($notWorking){
echo "Hopefully, they were not working on any project at the moment so we just ";
}
//if there were no checkboxes selectes, display a message to tell people to select at least one programmer
if ($affected_rows==0){
echo "No programmers to delete. Please select at least one.";
exit;
}
//display how many programmers were deleted from the 'programmers' table and also what are their names
else{
echo "deleted ".$affected_rows." programmer(s)";
echo ". Successfully deleted:<ul>";
for($i=0;$i<count($nameDeletedProgs);$i++){
echo "<li>".$nameDeletedProgs[$i]." ".$surnameDeletedProgs[$i]."</li>";
}
echo "</ul>";
}
}
$query = "SELECT * FROM programmer";
$resultset = $conn->query($query);
while ($row = $resultset->fetch())
{
echo "<p class='col'>";
echo "<input type='checkbox' name='programmers[]' id='programmer".$row['programmer_id']."' value='".$row['programmer_id']."'>";
echo "<a href='' class='help tip-below' data-tip='".projects($row['programmer_id'])."'><label for='programmer".$row['programmer_id']."'> ".$row['programmer_name']." ".$row['programmer_surname']."</label></a>";
echo "</p>";
}
?>
<input type="submit" value="Delete Programmer(s)" class="sub-del submit-btn">
</form>
how would i go about refreshing a page after i have submitted a form and done some php stuff with it. Heres my form and the php so far.
<form class="removeform"action='peteadd.php'method='post' enctype='multipart/form-
data' name='image_remove_form' >
<?php
include '../inc/connect.php';
$q = "SELECT * FROM gallerythumbs WHERE gallery = 1";
if($r = mysql_query($q)){
while($row=mysql_fetch_array($r)){
echo "<div class='thumb'>",
"<input type='checkbox' name='remove[{$row['id']}]'>",
"<label for='Remove'><span class='text'>Remove</span></label>",
"<br />",
"<img class='thumbnail' src='{$row['filename']}'
alt='{$row['description']}' />",
"</div>";
}
}
else{
echo mysql_error();
}
?>
<input type='submit' name='submit' value='Remove' />
</form>
</div>
<?php
include '../inc/connect.php';
//if delete was checked, delete entries from both tables
if(isset($_POST['remove'])){
$chk = (array) $_POST['remove'];
$p = implode(',',array_keys($chk));
$t = mysql_query("SELECT * FROM galleryimages WHERE id IN ($p)");
$r = mysql_query("SELECT * FROM gallerythumbs WHERE id IN ($p)");
$url=mysql_fetch_array($t);
$image=$url['filename'];
$url2=mysql_fetch_array($r);
$image2=$url2['filename'];
if ($t){
unlink($image);
unlink($image2);
$q = mysql_query("DELETE FROM galleryimages WHERE id IN ($p)");
$s = mysql_query("DELETE FROM gallerythumbs WHERE id IN ($p)");
}
else{
echo "<span class='text'>
There has been a problem, go back and try again.
<br />
<a href='peteadd.php'>Back</a>
</span>";
}
}
else{
echo "<span class='title'>
There are no images in the gallery
<br />
<a href='peteadd.php'>Add Images</a>
</span>";
}
?>
This for display some thumbnails that are saved in mysql with a remove checkbox above them. When I check them then submit the form the are deleted from the direcotries and the mysql tables ok, but how can I refresh the page so the deletion is obvious?
Thanks for looking
what you are describing sounds like you are displaying your page and within it you run some additional code - like deletion - so when you post your form you end up with images being pull from database and then removed
you should run your logic first and only then display page - that way you will be first deleting your records and then when it came to get data from database it will get right data (without records already deleted)
any other soultion will be nothing but hacky way to bypass problem that souldn't exist in the first place :)
You cannot directly refresh a page with PHP, but you can echo out a refresh tag like this
echo '<meta http-equiv="refresh" content="0">'
, or you can do it with javascript, like
location.reload(true);