Jump to content

Removing entries from database


Schlo_50

Recommended Posts

I have a flat file database and one of the tables (stock_cat.txt) contains category names along with a unique id for each. I am creating a script which will remove categories that I select from the .txt file. The problem is, even when I pass a unique category id through the URL every single category gets deleted in the table, and not the one associated with the id. Code as follows:

 

$file = file("data/stock_cat.txt");

foreach($file as $key => $val){

$data[$key] = explode("|", $val);

print $_GET['cid'];

if ($_GET['cid'] = $data[$key][2]) {

  unset($file[$key]);
  $fp = fopen("data/stock_cat.txt", "w");
  fwrite($fp, implode('', $file));
  fclose($fp);
print "Deleted";
}
}

 

Any suggestions/snippets welcome!

Thanks

Link to comment
https://forums.phpfreaks.com/topic/98209-removing-entries-from-database/
Share on other sites

<?php
$file = file("data/stock_cat.txt");

foreach($file as $key => $val){
  $parts = explode("|", $val);
  if($_GET['cid'] == $parts[2]) {
    unset($file[$key]);
  }
}
$fp = fopen("data/stock_cat.txt", "w");
fwrite($fp, implode('', $file));
fclose($fp);
print "Deleted";
?>

or

<?php
$file = file("data/stock_cat.txt");

$fp = fopen("data/stock_cat.txt", "w");

foreach($file as $key => $val){

    $data = explode("|", $val);

    if ($_GET['cid'] != $data[2]) {
        fwrite($fp, $val);     // write if NOT the one to be deleted
    }
}
fclose($fp);
print $_GET['cid'] . ' deleted';
?>

Well, if you are gonna do it that way, at least remove the $key variable as it's not needed  :)

 

 

<?php
$file = "data/stock_cat.txt";
$fp = fopen($file, "w");
foreach(file($file) as $val){
    $data = explode("|", $val);
    if ($_GET['cid'] != $data[2])
        fwrite($fp, $val);     // write if NOT the one to be deleted
}
fclose($fp);
print $_GET['cid'] . ' deleted';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.