views:

357

answers:

1

hi,

I pieced together the script below from various tutorials, examples, etc...

Right now the script currently saves Id, Name, Url with a "|" delimiter to a text file Db like:

1|John|http://www.john.com|
2|Mark|http://www.mark.com|
3|Fred|http://www.fred.com|

But I'm having a hard time trying to make the "UPDATE" and "DELETE" buttons work.

Can someone please post code which will:

  • let me update/save any changed data for that row (for UPDATE button)
  • let me delete that row (for DELETE button)

PLEASE copy n paste the code below and try for yourself. I would like to keep the output format of the script below too.

thanks D-


<?php

$file = "data.txt";
$name = $_POST['name'];
$url = $_POST['url'];

$data = file('data.txt');
  $i = 1;
    foreach ($data as $line) {
    $line = explode('|', $line);
  $i++;
}

if (isset($_POST['submits'])) {
 $fp = fopen($file, "a+");
   fwrite($fp, $i."|".$name."|".$url."|\n");
  fclose($fp);
}


?>
<html>
<head>
</head>
<body>
<br>
<form name="form1" action="thispage.php" method="POST">
<input type="text" name="name">
<input type="text" name="url">
<input type="submit" name="submits" value="ADD"><br>
</form>
<form name="form2" action="thispage.php" method="POST">
<?php

   $display = file("data.txt");
       for ($i=0; $i<=count($display)-1; $i++) {
       $lines = explode("|",$display[$i]);

       print('<input type="hidden" name="id" value="'.$lines[0].'">
                 <input type="text" name="name" value="'.$lines[1].'">
                 <input type="text" name="url" value="'.$lines[2].'">
                 <input type="submit" name="update" value="UPDATE">
                 <input type="submit" name="delete" value="DELETE"><br>');
       }

?>
</form>
</body>
</html>
A: 

I'm not just going to post code for you. (It's late and I guarantee typos if I do)

First off, you need to mark the form fields in your output to identify each line. You can do that by using arrays. For example instead of name="url" you can use name="url[]" and your $_POST variable will contain an array - the key will determine what line you're messing with.

You also need something to delete with. This can be a plain link, or a checkbox. A checkbox is probably better, since it will let you delete many rows at once. Get rid of the "delete" submit button you have.

Once you have those in place, you can just iterate though each line in your $_POST variable (and database file) and edit or delete as necessary.

Syntax Error