Search code examples
phpstringquotesdouble-quotes

How to put css selectors into php generated html code


I'm trying to make one little prototype on PHP and Wordpress, and I can't find out what is wrong with this.

This code is fine:

<?php
    mysql_connect( "localhost", "root");
    mysql_select_db( "wp");
                  
    $result = mysql_query("select score from test"); 
    $argument = mysql_query("select level from test");
    echo "<table>\n";
    echo "<tfoot><tr>\n";
    while ($myarg = mysql_fetch_row($argument))
    {
    printf("<th>%s</th>\n", $myarg[0]);
    }
    echo "</tr></tfoot>\n";
    echo "<tbody><tr>\n";
    while ($myres = mysql_fetch_row($result))
    {
    printf("<td>%s</td>\n", $myres[0]);
    }
    echo "</tr></tbody>\n";
    echo "</table>\n";  
?>

But when I add selector to table, like this:

echo "<table id="data">\n";

I've got the following error on the page:

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in ... ...

Same thing when I add styles.


Solution

  • The problem

    The problem is that you try to print a character that has a meaning in the PHP language. You try to print a double quote but in this case it means end of the string (that you started with the first double quote) for the praser.

    Solution

    Use single quotes for echo:

    echo '<table id="data">\n';
    

    Escape the special character you want to print:

    echo "<table id=\"data\">\n";
    

    Explanation

    You got a prase error because when the praser arrives at the end of echo "<table id=" part, it expects a ; as a close for your command or a comma with other parameters. That is the reason why it says:

    Parse error: syntax error, unexpected T_STRING, expecting ',' or ';'

    Also it says he got a T_STRING (instead of the expected values explained previously) that is the data you typed.
    Furthermore the error message says that he is a syntax error. So it has a problem with what you typed, you used the wrong syntax.

    Conclusion

    Analyse your error messages, the praser gives them to help you to solve your problem. Also copying the error message to an online search engine can solve you a problem incredibly fast.