2017-02-17 129 views
2

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

“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> 

我输入一些食品名称后,它发送到文件调用“foodscript.php”

<?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

所以我的问题是如何编辑/更新或删除我的数据“寿司”使用具有删除和编辑按钮的新窗体?如果你们有更好的想法该怎么做,你介意让我看看这个过程或方法吗?我只是一个学生。

很多谢谢。

+1

不要将数据存储在HTML中,将其存储在数据库中。您可以在那里编辑/删除数据。鉴于这个问题,你真正应该从PHP/MySQL的一些教程开始。 – David

+0

@大卫哦,我的学校还没有教这个阶段,但我想在网上找到它。 –

+0

然后,您正在寻找的Google搜索词是“PHP MySQL教程”。 – David

回答

0

您尚未为表单定义方法,因此浏览器不知道如何发送它。
将表单的方法属性设置为“post”。
如果仍然不行,试试这个代码,并告诉我们你得到了什么:
echo $_POST["foodname"];

+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文件是不正确的做法......但我想这与学校有关。

+0

好的,谢谢Effe,我会用你的代码对它进行实验,然后回过头来看看它的工作原理。 –