2017-02-17 118 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,我會用你的代碼對它進行實驗,然後回過頭來看看它的工作原理。 –