2

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>\n";
$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.)

1
  • 1
    is it a top priority to use static files? if not, db could do the job. if it is - you didn't tell that much about your html file (btw. you're opening a php file - not html). if <tr> is all you have in your file, you could use file_get_contents and then insert your new <tr> at the beginning of the array... Commented Nov 22, 2012 at 20:48

2 Answers 2

1

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>\n";

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I know the variables weren't very clear... Your method is working well but the problem is that i do have got some content before the table rows. Is it possible to check if there's content before the row and if there is, add a predefined content from a text file and then the row? My list is static and I don't delete any of the rows. If i can't do it like that, I'll have to use an iframe I guess...
There are many ways to achieve the end result, but to find the optimal one, you should probably tell us what you're trying to do. I know you're creating a to-do list without checkboxes, but what other tools are available? Can you use a database? Does the to-do list have to be a static HTML file, or can it be served by the PHP file directly?
In terms of parsing an HTML file, the best way is to use a Document Object Model (DOM) parser, which allows you to access specific nodes/tags (e.g. the <table> tag), and then manipulate it (e.g. insert a new <tr> row to the beginning). Of course, you can resort to more low-level methods, like using strpos() to search for the character position of <table> and then add your row after that. Personally, I wouldn't do it that way because you can end up with malformed HTML.
1

A bit shorter, but this should do the trick (untested)

<?php
if (!emtpy($_POST['since']))//check using empty, it checks if postvar is set, and if it's not empty
{//only open the file if you're going to use it
    $file = fopen('index.php','a');//no need for read access, you're not reading the file ==> just 'a' will do
    $row = '<tr><td class="since"'.$_POST['since'].'</td>
            <td class="due">'.$_POST['due'].'</td>
            <td class="content">'.$_POST['user'].'</td></tr>';//don't forget to close the row
    fwrite ($file,$row);
    fclose($file);
}
?>

BTW, your if statement doesn't quite cut it:

if ($_POST["since"]  <> "");
{

in PHP != and !== are the operators you're looking for (is not equal too), and an if statement isn't followed by a semicolon.
You're also assigning a lot of post variables to a new variable, just to concatenate them into a string, there's absolutely no need to do that:

$newString = 'Concat '.$_POST['foo'].'like I did above';
$newString = "Same ".$_POST['trick'].' can be used with double quotes';
$newString = "And to concat an array {$_POST['key']}, just do this";//only works with double quotes, though

Update:
to answer your question in the comments below: here's what you need in order to parse the html, and append/prepend the desired elements:

$document = new DOMDocument();
$document->loadHTML(file_get_contents('yourFile.html'));
//edit dom here
file_put_contents('yourFile.html',$document->saveHTML());

Spend some time here to find out how you can add/create/alter any number of elements in the DOM. Methods that might be of interest to you are: createDocumentFragment, createElement, and all JavaScript lookalikes: getElementById, getElementsByTagName, etcetera...

11 Comments

First thanks for the answer! I think it'll be easier to use a plain html file only for the rows and an iframe to display the content. Do You know how to add a stylesheet for the content in the iframe? It is a php script right? The solution at the bottom worked better for me.
@user1846030: I'm not sure if I get what you're on about here, but if you need an extra CSS in an iFrame, just add it to the header of the document in that iFrame... on the rows an alternative approach is to parse the HTML into a DOMDocument object, append and write the file again, that way, you avoid bad formatted html. But again, on the iFrame thing: best post a new question about that
No, I'm just going to leave it. My problem is that i can't add any content to the head of the file because a new tr will be added above it!
That's why you should parse the DOM, that way you can append and prepend where you want
Ok, that's what I wanted. But how do you do this? Any good explanation website for this?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.