Search code examples
phpsqlunlink

Problems deleting File PHP


This is my code to pull information from my sql database and then I want to delete the .txt files in each directory, but I can't seem to figure out why it won't delete the files.

<?php

session_start();
$user = $_SESSION['SESS_USERNAME'];

$id = array();
$id = $_POST['selected'];

//Include database connection details
require_once('config_order.php');

//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link) {
    die('Failed to connect to server: ' . mysql_error());
}

//Select database
$db = mysql_select_db(DB_DATABASE);
if (!$db) {
    die("Unable to select database");
}

//Create query
$query = mysql_query("SELECT * FROM  `PropertyInfo` WHERE  `order_number` =  '$id[0]'");

// display query results

while ($row = mysql_fetch_array($query)) {
    $c_name = $row['clientname'];
    $sitestreet = $row['sitestreet'];              
    $inspector = $row['inspector'];
}
mysql_close($link);

$client_name = str_replace(" ", "_", $c_name);
$site_street = str_replace(" ", "_", $sitestreet);

$client_name = "{$client_name}.txt";
$site_street = "{$site_street}.txt";

$client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
$inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";

if (unlink($client_path . "/" . $client_name)) {
    echo 'File Deleted';
} else {
    echo 'File could not be deleted';
}
?>

Solution

  • I think this is because your while loop is overwriting the $c_name, $sitestreet and $inspector variables. This means you will only ever delete the last file.

    Is this what you were trying to do? (Edited Again...)

    $query = mysql_query("SELECT * FROM `PropertyInfo` WHERE `order_number` IN (".mysql_real_escape_string(implode(',',$id)).")");
    
    while ($row = mysql_fetch_array($query)) {
    
      $inspector = $row['inspector'];
      $client_name = str_replace(" ", "_", $row['clientname']).'.txt';
      $site_street = str_replace(" ", "_", $row['sitestreet']).'.txt';
    
      $client_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Clients";
      $inspection_path = "/var/www/vhosts/default/htdocs/Members/$user/$inspector/Orders/Inspections";
    
      if (!file_exists($client_path.'/'.$client_name)) {
        echo "File $client_path/$client_name does not exist!\n";
      } else echo (unlink($client_path.'/'.$client_name)) ? "File $client_path/$client_name was deleted\n" : "File $client_path/$client_name could not be deleted\n";
    
    }
    mysql_close($link);