getaway
getaway

Reputation: 8990

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

Upvotes: 3

Views: 648

Answers (5)

user229044
user229044

Reputation: 239581

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 ?>

Upvotes: 2

Josh K
Josh K

Reputation: 28893

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>';

Upvotes: 4

gen_Eric
gen_Eric

Reputation: 227310

 echo "<tr><td><img src='images/{$row['picture']}' alt='{$row['username']}' /></td>";

Only double quoted strings will parse PHP variables.

Upvotes: 3

Fanis Hatzidakis
Fanis Hatzidakis

Reputation: 5340

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.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 158005

?>
<tr><td><img src="images/<?=$row['picture']?>" alt="<?=$row['username']?>" /></td>
<?

Upvotes: 3

Related Questions