PHP(编辑和删除html文件)

时间:2017-02-17 11:46:53

标签: php html mysql

我在学校学到的是使用 file_put_content()输入和显示数据。但我无法弄清楚如何编辑/更新或删除内部数据。

我的" form.php"

    <!--Form to the php script-->

<form action="foodscript.php"method="post">
  I love:<br>
  <input type="text" name="foodname" value="">
  <input type="submit" value="Submit">
</form>

输入一些食物名称后,它会发送到文件调用&#34; foodscript.php&#34;

<?php
  //This is where my input data is being process to the txt file.
   $name= $_POST['foodname'];

  //This is where my data would be store in this file.
   $file= "foodhistory.html"; 

  //The function is begins to created new file and store my data on it.
  file_put_contents($file, $name . PHP_EOL, FILE_APPEND);

 ?>

然后, foodhistory.html 已创建并存储我已在表单上输入的数据。数据在 foodhistory.html 中调用&#34; Sushi&#34;

所以我的问题是如何编辑/更新或删除我的数据&#34; Sushi&#34;使用具有删除和编辑按钮的新表单?如果你们有更好的想法如何去做,你介意向我展示这个过程或方法吗?我只是一名学生。

非常感谢。

2 个答案:

答案 0 :(得分:1)

首先,您必须知道要编辑/删除哪个元素,因此表单必须要求食物的名称。

鉴于此,要编辑/删除,您可以执行类似的内容

<?php

$file = 'foodhistory.html';

$oldName = $_POST['oldname'];
$newName = $_POST['newname'];
$action  = $_POST['action']; // delete or edit

// this function reads the file and store every line in an array
$lines = file($file);

$position = array_search($oldName, $lines);

if($position) {
    exit('Food not found.');
}

switch($action) {
    case 'delete':
        unset($lines[$position]);
        break;
    case 'edit':
        $lines[$position] = $newName;
        break;
}

file_put_contents($file, implode(PHP_EOL, $lines)); // overwrite stuff on the file with fresh data

PS:您显然知道HTML文件中的商店数据不是正确的方式......但我认为这与学校有关。

答案 1 :(得分:0)

您还没有为表单定义方法,因此浏览器不知道如何发送它。
将表单的method属性设置为&#34; post&#34;。
如果它仍然无法正常工作,请尝试使用此代码告诉我们你得到了什么:
echo $_POST["foodname"];