what is wrong with this php echo statement?
sorry i know this is a basic question, but i have been trying for hours and i cnt seem to think what is wrong with this!
echo '<tr><td><img src="images/$row['picture']" alt=开发者_如何学编程"' . $row['username'] . '" /></td>';
is thier a more cleaner way to do this and and error free.
thanks
You are missing a few '
's in there.
I would do it as follows:
echo '<tr><td><img src="images/' . $row['picture'] . '" alt="' . $row['username'] . '" /></td>';
There are a few other ways of doing this, but I wouldn't recommend either using short tags or inserting variables into strings ever. Doesn't matter if it is double quoted, terminate the string and concatenate. It is much simpler on the eyes and makes for cleaner code.
You could even avoid string concatenation completely by using ,
's to separate echo arguments.
echo '<tr><td><img src="images/', $row['picture'],
'" alt="', $row['username'], '" /></td>';
?>
<tr><td><img src="images/<?=$row['picture']?>" alt="<?=$row['username']?>" /></td>
<?
echo "<tr><td><img src='images/{$row['picture']}' alt='{$row['username']}' /></td>";
Only double quoted strings will parse PHP variables.
The first '
opens a string. You're accidentally closing that string at $row['
, causing an error. You need to either close your string earlier and echo $row['picture']
separately (see below), or use double quotes ("
) which allow for variable interpolation.
Also, a word of advice: Don't use concatenation (the .
operator) when echoing in PHP. Echo accepts multiple comma-separated arguments which incurs none of the overhead of string concatenation:
echo '<tr><td><img src="images/', $row['picture'], '" alt="',
$row['username'], '" /></td>';
As a side note, the same applies to <?=
, which is identical to <?php echo
:
<?= $value, ' + 1 = ', $value + 1 ?>
You need to escape $row['picture'] as well
echo '<tr><td><img src="images/' . $row['picture'] . '" alt="' . $row['username'] . '" /></td>';
If you want a cleaner way consider the following:
echo "<tr><td><img src='images/{$row['picture']}' alt='{$row['username']}'/></td>";
If you have double quoted strings you can include array values inline as long as they're enclosed in { }. Ofcourse you have to change the double quotes in the html elements to single, or escape them.
精彩评论