[英]code only working after second click, simple php
我正在嘗試在 php 中創建一個簡單的程序,該程序讀取帶有歌曲的文本文件,然后將它們打印在屏幕上,每首歌曲旁邊都有一個刪除按鈕,然后當您單擊刪除按鈕時,歌曲應該刪除。 新文件被寫入 txt 文件,並且應該在屏幕上刷新。 我的代碼僅在第二次點擊后才有效。 第一次單擊實際上確實修改了 txt 文件,但屏幕上的代碼不會刷新。
謝謝
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Music</title>
<body>
<h1>My Music</h1>
<p>My Library</p>
<?php
//read file
$myFile = "test.txt";
//file to array
$lines = file($myFile);
//set array length
$length = count($lines);
//print array on screen with delete button
for ($i = 0; $i < $length; $i++) {
echo $lines[$i] . '<form action="index.php" method="post">
<button type="submit" name="test" value="' . $i . '">Delete</button><br><br></form>';
}
//after clicking delete box remove song from array
if (isset($_POST['test'])) {
//getting song number to remove
$songNumber = $_POST['test'];
//removing song from original array
array_splice($lines, $songNumber, 1);
//open test.txt again
$myFile2 = fopen("test.txt", "w") or die("Unable to open file!");
//set updated array length
$length = count($lines);
//write array to test.txt
for ($i = 0; $i < $length; $i++) {
$txt = $lines[$i];
fwrite($myFile2, $txt);
}
}
?>
</body>
</html>
我正在使用的文本文件
1. turkish march
2. claire de lune
3. symphony no. 9
4. swan lake
5. imperial march
6. helter skelter
看看你的代碼做的事情的順序。 首先它從文件中讀取並顯示數據。 然后它從文件中刪除一行。 在文件已經顯示之后。
只需交換事件的順序:
if (isset($_POST['test'])) {
// perform your delete
}
// Display the contents of the file
$myFile = "test.txt";
// etc.
for ($i = 0; $i < $length; $i++) {
// ...
}
您正在閱讀文件,然后刪除標題,當您單擊按鈕時,您閱讀了未修改的版本,然后對其進行了修改,這就是它在第二次刷新時起作用的原因……或單擊……更改代碼的順序。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Music</title>
<body>
<h1>My Music</h1>
<p>My Library</p>
<?php
//after clicking delete box remove song from array
// remove file first if needed...
if (isset($_POST['test'])) {
//getting song number to remove
$songNumber = $_POST['test'];
//removing song from original array
array_splice($lines, $songNumber, 1);
//open test.txt again
$myFile2 = fopen("test.txt", "w") or die("Unable to open file!");
//set updated array length
$length = count($lines);
//write array to test.txt
for ($i = 0; $i < $length; $i++) {
$txt = $lines[$i];
fwrite($myFile2, $txt);
}
}
//read file
$myFile = "test.txt";
//file to array
$lines = file($myFile);
//set array length
$length = count($lines);
//print array on screen with delete button
for ($i = 0; $i < $length; $i++) {
echo $lines[$i] . '<form action="index.php" method="post">
<button type="submit" name="test" value="' . $i . '">Delete</button><br><br></form>';
}
?>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.