Tuesday, March 1, 2011

changing tables rows to links

Hello, I am trying to change the rows output by php in a table to links. I have added the a href tags to the example below, however it results in an unexpected T_VARIABLE. I have tried it without the extra quotes, but this displays a blank table. I am not sure what the flaw in the logic is.

while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td><a href="$cell"</a></td>";

    echo "</tr>\n";
}
From stackoverflow
  • You have to escape the double quotes:

    foreach($row as $cell)
            echo "<td><a href=\"{$cell}\"</a></td>";
    

    By the way, I think that a good habit is to sorround variables inside strings with the curly braces to improve readibility of the code.

    Huppie : You missed the second mistake, it won't error in PHP but will give flawed HTML. There's a missing > and content of the HREF element.
    Davide Gualano : You are right, I focused on the php part and didn't notice the html error :)
  • You need to escape the double quotes as that is your string delimiter.

     echo "<td><a href=\"$cell\">Link</a></td>";
    

    Or use single quotes

     echo '<td><a href="' . $cell .'">Link</a></td>';
    

0 comments:

Post a Comment