2

This is my PHP/MySQL script:

<?php
    mysql_connect('localhost', 'root', 'test') or die (mysql_error());
    mysql_select_db('info1') or die (mysql_error());
    $result = mysql_query("SELECT * from automobiles");

    //Table starting tag and header cells
    while($row = mysql_fetch_array($result)){
        //Display the results in different cells
        echo "<dd><dl><img src=' " . $row['image'] . " '>" . $row['manufacturer'] ." " . $row['model'] . "</dd></dl>";
        echo "<dd><dl>" . $row['carinfo'] . "</dd></dl>";
    }

    //Table closing tag
    echo "</table>";
?>

However, would it work if I did it this way:

{$myvariable}

Is it a good idea to code the variables with the braces, or as:

echo " . $row['variable']. "

Any help is appreciated, thanks!

2 Answers 2

7

You can do this:

echo "<dd><dl>{$row['carinfo']}</dd></dl>";

You cannot do this:

echo "<dd><dl>$row['carinfo']</dd></dl>";

This also wont work:

echo '<dd><dl>{$row['carinfo']}</dd></dl>';

Your output would actually be:

<dd><dl>{$row[ SOME PHP ERROR

This is due to using single quotes instead of double quotes. And the error would be because you did not escape the single quotes inside the variable.

If you did this:

echo '<dd><dl>{$row["carinfo"]}</dd></dl>';

Your output would actually be:

<dd><dl>{$row["carinfo"]}</dd></dl>

For the same single quote vs double quote reasoning.

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

3 Comments

+1 was going to say the same thing that I saw 2 new answers :P
To add a bit information: please keep in mind that "inlining" variables works only if your string delimiters are double-quotes (i.e. "). Strings wrapped with single quotes (') won't get processed (i.e. no variables or escape characters will be replaced)
@Martin -- that aspect has been added.
4

I personally prefer using the " " . $row['variable']. " " syntax because it's easier to read code, specially if you have a code syntax highlighter. But using this syntax is acceptable: "{$var['field']}".

Comments

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.