duanbi1888 2012-11-22 20:40
浏览 29

PHP:将表格行添加到HTML文件

I'm trying to add a table row generated in PHP to a HTML file. Actually I've done this with a simple HTML form and some PHP code, but I would like the new row to be added at the top of the table, not at the bottom... (It's going to be a to-do list for my homework, but without checkboxes.)

Here's the PHP code:

<?php
$file = fopen("index.php","a+") or exit("Unable to open file!");
$since = $_POST["since"];
$since2 = "<tr><td class=\"since\">$since</td>";
$due = $_POST["due"];
$due2 = "<td class=\"due\">$due</td></tr>
";
$user = $_POST["user"];
$user2 = "<td class=\"content\">$user</td>";

if ($_POST["since"] <> "");
{
    fwrite ($file,"$since2$user2$due2");
}

fclose($file);
?>

Can anyone help me? (Yeah I know the code isn't clean because it's my first attempt to write PHP.)

Here's an example of a tr made with the code:

<tr><td class="since">Thu 22th  Nov</td><td class="content">example</td><td class="due">Tue 27th  Nov</td></tr>

My main point is to have a new tr added on the top! Really appreciate any help! (I've looked around and hope this question hasn't been asked yet.)

  • 写回答

2条回答 默认 最新

  • dongyan3237 2012-11-22 20:50
    关注

    To add it to the beginning of the file, you can read its contents, add it to the end of your new row, and then write the whole thing back to the file.

    // read the original file
    $original_list = file_get_contents("index.php");
    
    // use the writing mode to overwrite the file
    $file = fopen("index.php","w") or exit("Unable to open file!");
    
    $since = $_POST["since"];
    $since2 = "<tr><td class=\"since\">$since</td>";
    
    $user = $_POST["user"];
    $user2 = "<td class=\"content\">$user</td>";
    
    $due = $_POST["due"];
    $due2 = "<td class=\"due\">$due</td></tr>
    ";
    
    if ($_POST["since"] <> "");
    {
        fwrite($file,"$since2$user2$due2$original_list");
    }
    
    fclose($file);
    

    This is not the optimal way to build a to-do list, but we don't know enough about your homework and the requirements to further improve the answer.

    Another tip: Avoid using meaningless variable names like $since2 and $due2, even if they are temporary in nature. By using better names like $since_cell and $due_cell, the code becomes much easier to understand, even without comments.

    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭