Delete file from folder and mysql joined table - php

I have a file upload system where I can delete from MySQL DB and from the folder.
The only problem is that all the files in the folder are deleted instead of just the single one. Each folder is a custom folder with a person's name.
I have a joined table where the id's of two tables are equal. I need the joined tabled to receive the name of the person to know the file location.
This is my working code so far where multiple files are deleted instead of the one I selected:
$analyse = mysqli_query($conn, "SELECT *
FROM analyse
INNER JOIN persons ON
analyse.id_person = persons.id");
while ($row = mysqli_fetch_array($analyse)) {
$img = $row['img_name'];
$name= $row['name'];
$frontname= $row['frontname'];
$image_url = "../persons/{$name} {$frontname}/analyse/{$img}";
$result = mysqli_query($conn, "DELETE FROM analyse WHERE id=$id");
unlink($image_url);
if($result){
header('Location: ' . $_SERVER['HTTP_REFERER']);
} else {
echo "Failed to delete";
}
}
For example: Person X with id 15 has three images with different ids but each time with the ID(15) of the person. I want to be able to delete the single selected file instead of all the files with id 15.
UPDATE
I found the solution, the ID that came through for deleting was always the first in my DB row. The fetching of my array was wrong and my ID consequently too.
Thanks for the answers.

Try using Limit 1 with your delete Query.
$analyse = mysqli_query($conn, "SELECT *
FROM analyse
INNER JOIN persons ON analyse.id_person = persons.id");
while ($row = mysqli_fetch_array($analyse)) {
$img = $row['img_name'];
$name= $row['name'];
$frontname= $row['frontname'];
$image_url = "../persons/{$name} {$frontname}/analyse/{$img}";
$result = mysqli_query($conn, "DELETE FROM analyse WHERE id=$id LIMIT 1");
unlink($image_url);
if($result){
header('Location: ' . $_SERVER['HTTP_REFERER']);
} else {
echo "Failed to delete";
}
}

Related

delete image from row that has been expired

Hey I have a php code that checks which rows date got expired and delete them , one of the columns is an image name that was uploaded to the server via ftp, when I delete all expired records I also want to delete the images that is attached to them.
I read about the unlink command on php but I don't see how I can apply it to all of the images at once.
I have this code that I just rambled for example cause I don't really know how to do it..
$sql = "DELETE FROM table WHERE date < NOW()";
mysqli_query($conn,$sql);
$file = "public_html/images/".//Here should go the image name;
unlink($file);
if($sql)
{
echo "Records were deleted";
}
?>
Can anyone tell me how can I delete all images that are attached to the deleted rows?
IF you want to delete the rows from the table in your database and at the same time delete the images from the folder on the server where you keep them then you will have to process each delete candidate one at a time, so that you can get the filename from the row to accomplish the file delete at the same time sa deleting the row.
// connect to database
$base_path = 'public_html/images/';
$del_count = 0;
// SELECT all the delete candidates
$sql = "SELECT id,image FROM table WHERE date < NOW()";
$sel4del = mysqli_query($conn,$sql);
if ( ! $sel4del ) {
echo $sel4del->error;
exit;
}
// prepare a delete by id
$sql = 'DELETE FROM table WHERE id = ?';
$delrow = mysqli_prepare($conn,$sql);
if ( ! $delrow ) {
echo $delrow->error;
exit;
}
// Process all the delete candidates one by one
while ($row = $sel4del->fetch_object() ) {
// remove the file from disk
unlink($base_path . $row->image);
$del_count++;
// bind the current id to the prepared delete query
$delrow->bind_param('i', $row->id);
// execute the delete of this one row
$delrow->execute();
}
echo 'images removed = ' . $del_count
?>

Display more than one row from SQL SELECT

I want to display all of the rows shown in the picture where CID = 1.
Here is my PHP code with SQL:
`
$contractCount = 1;
$sql = "SELECT categories.categoryID
FROM categories
LEFT JOIN link
ON categories.categoryID = link.categoryID
WHERE link.CID = '$contractCount'";
$res = $con->query($sql);
if (!$res) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while ($row = mysqli_fetch_array($res)) {
echo $row['categoryID'];
}
Here is an image showing the table in PHPMyAdmin called categories.
So I need output as ITSM, Mar and HrAd but I am only getting ITSM and not the rest.
EDIT 1: The LEFT JOIN makes no difference here, the link table has no bearing on the SELECT statement
EDIT 2: I have solved the problem, my mistake was that I had the table names the wrong way round in the SQL query.
You need to use the function mysql_fetch_row, this will fetch a row and move the pointer to the next one.
while ($row = mysqli_fetch_row($res)) {
echo $row['categoryID'];
}

how can i move multiple files where the file names and paths are in columns of a database table?

files locations are stored in database, and when i delete the table records/rows from the files table, i need to move the files to another directory (an archive directory).
there are 2 tables at play. a jobs table and files table. jobs have files. when deleting a job i need to delete the job entry from jobs table, but also i need to delete file(s) entries from files table, but the actual files are not be be deleted... they are to be moved (archived).
here is the entire delete script that is attempting to delete records from 2 tables and move files to another folder. the deleting of records from both tables works. only one file is moved though. if there are multiple files, it doesn't move all the files. i tried wrapping the rename line with a while line. i tried wrapping the entire if($dbrow) section in the same while clause. i can't get this to work with while to loop through all the files. maybe a foreach is in order? how can i do that?
<?php
/*
delete-job.php
Deletes job entry from the 'jobs' table and also deletes file entry/entries from 'files' table and moves (archives) files
*/
//check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
//get id value
$id = $_GET['id'];
$dbresult = mysql_query("SELECT jobs.*, files.* FROM jobs INNER JOIN files WHERE files.jobid = jobs.id") or die(mysql_error());
$dbrow = mysql_fetch_array($dbresult);
if($dbrow) {
$name = $dbrow['name'];
$path = $dbrow['path'];
$count = $dbrow['count'];
$approved = $dbrow['approved'];
$approved_date = $dbrow['approved_date'];
$jobid = $dbrow['jobid'];
$timedateadded = $dbrow['timedateadded'];
$currentdate = date("m-d-Y_H-i-s");
$archivepath = "uploads/archive/".$name;
rename("".$path."", "".$archivepath."");
//delete the entry/entries
//$result = mysql_query("DELETE FROM jobs WHERE id=$id") or die(mysql_error()); //delete from just jobs table
$result = mysql_query("DELETE jobs, files FROM jobs INNER JOIN files WHERE jobs.id = $id AND files.jobid = jobs.id") or die(mysql_error()); //also delete file records from files table that belong to the deleted jobs
header("Location: view-jobs.php"); //redirect back to the view page
} //end if($dbrow)
} //end if isset
else { //if id isn't set, or isn't valid...
header("Location: view-jobs.php"); //redirect back to view page
}
?>
Is this what you want or did you try that already? (Edited)
<?php
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
$dbresult = mysql_query("SELECT jobs.*, files.* FROM jobs INNER JOIN files WHERE files.jobid = jobs.id") or die(mysql_error());
while($dbrow = mysql_fetch_array($dbresult))
{
$name = $dbrow['name'];
$path = $dbrow['path'];
$count = $dbrow['count'];
$approved = $dbrow['approved'];
$approved_date = $dbrow['approved_date'];
$jobid = $dbrow['jobid'];
$timedateadded = $dbrow['timedateadded'];
$currentdate = date("m-d-Y_H-i-s");
$archivepath = "uploads/archive/".$name;
rename("".$path."", "".$archivepath."");
//delete the entry/entries
//$result = mysql_query("DELETE FROM jobs WHERE id=$id") or die(mysql_error()); //delete from just jobs table
}
$result = mysql_query("DELETE jobs, files FROM jobs INNER JOIN files WHERE jobs.id = $id AND files.jobid = jobs.id") or die(mysql_error()); //also delete file records from files table that belong to the deleted jobs
header("Location: view-jobs.php"); //redirect back to the view page
}else { //if id isn't set, or isn't valid...
header("Location: view-jobs.php"); //redirect back to view page
}
?>

Checking if variable is empty

First I will paste my code than explain.
while($row = mysqli_fetch_assoc($result)) {
$id=$row['id'];
$username=$row['username'];
$email=$row['email'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
$motto=$row['motto'];
$bio=$row['bio'];
$result4 = mysqli_query($link, "SELECT * FROM photo where id='$id'");
while($row4 = mysqli_fetch_assoc($result4))
{
$image=$row4['filename'];
$src = (empty($image)) ? "upload/your-photo.jpg" : "site_images/$id/$image";
}
As you can tell the problem has to do with the image. I'm thinking the problem is where it SELECTS * FROM photo where id='$id' because this is in a while loop and if it is empty like it says in $src than it just moves on to the next person in line.
I was wondering how it would be possible to make this work? Right now it is just displaying the same image for every id when it should show the correct image.
You should just have one query with a join in it, to join the photo table.
I would try breaking out the conditional where you have the inner loop:
$result4 = mysqli_query($link, "SELECT * FROM photo where id='$id'");
while($row4 = mysqli_fetch_assoc($result4))
{
$image=$row4['filename'];
$src = "upload/your-photo.jpg";
if(!empty($image)) {
$src = "site_images/$id/$image";
}
}
If that doesn't work, try using:
strlen
and checking if it's equal to 0
Also, in your database, does your photo table have rows with with IDs but no photo file specified? Perhaps you are querying an empty table..

mySQL database: printing specific row or rows from a db table

please assist. i have a database with a couple of tables and rows and i want the php to print specific rows as and when i want it to. at the moment it renders all the content of the spesific table on my webpage. in future, i would like it to display the contents of a specific table if a cirtain user is logged in so im going to do that when i understand if statements and get over this hurdle 1st. my code is as follows:
<?php
include 'connect-mysql.php';
echo "<br/>";
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}
?>
To fetch specific rows from a table you have to include a WHERE clause in your SQL statement.
For example:
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer WHERE customer_id = 2";
Match the WHERE xxxxx clause to any column in your table
You need to specifiy yor criteria as a where clause in the SQL
$query = "SELECT CUSTOMER_NAME, RAMSCODE FROM customer where RAMSCODE = %1";
$result = mysql_query($query,mysql_real_escape_string($yourcode)) or die (mysql_error());
Also you really need to Read the Manuals!
As far as i've get what you want is to display only that row from customers table, which customer is logged in. you can use some thing like this:
while($row = mysql_fetch_array($result))
{
if($row['CUSTOMER_NAME'] == " //Customer Logged In (customer name from session)"){
echo "{$row['CUSTOMER_NAME']} <br>" .
"RAMSCODE: {$row['RAMSCODE']} <br>" ;
}else{
//do nothing or continue with printing all
}
}
Hope this helps.

Categories