r/PHPhelp • u/Steam_engines • May 20 '25
Echo punctuation
This line of code works:
echo "<td class='mid'><a href =\"http://www.abc.co.uk/edit2.php?ident=".$row['id']."\">Edit</a></td></tr>";
What I would like to do is have put a date insted of the word edit, like this:
echo "<td class='mid'><a href =\"http://www.abc.co.uk/edit2.php?ident=".$row['id']."\">.$row['rec_date'].</a></td></tr>";
This doesn't work. What am I doing wrong?
Help much appreciated
2
Upvotes
11
u/MateusAzevedo May 21 '25 edited May 21 '25
That's the reason why outputting HTML as PHP string isn't recommended, it gets messy real quick and hard to see errors (although a good IDE will highlight that better).
Instead, close the PHP tag and just output HTML as is, using the short echo syntax for variables and alternative syntax for control structures:
Notes:
1- Don't forget you need to escape output to prevent XSS;
2- Move all logic to the top, output to the bottom. That's the classic separation of concerns. It makes your code way easier to reason about;
If you want, a runnable example: https://3v4l.org/lIYpA#v8.4.7
2
u/Tontonsb May 21 '25
You could fix it by having each string start and end with the quotes, insert spaces around
.for visibility:In modern HTML (i.e.
<!doctype html>docs) you can enclose attribute in either single or double quotes and you can sometimes (if the value contains no spaces and some other special chars) even use no quotes at all. In your example the value (URL) contains=so you have to quote it.People use this to avoid the need for escaping quotes. It makes it easier to read. Your case could be written like:
The double quoted strings in PHP are used to enable string interpolation. That's a feature that allows placing variables directly in strings and PHP replaces them with their values. Your case (extracting values from array) has some special rules that you can read about in the docs, but TLDR is that you can write it like this:
or this:
3
u/equilni May 20 '25 edited May 21 '25
I would consider not echoing html lines and break in PHP to the html like below.
Now your example. Clean html, no
\escaping for quotes, matching quotes for attributes, etc. When you need PHP, call it.<?= $var ?>is short for<?php echo $var ?>,3
u/deWereldReiziger May 20 '25
I think you need " before and after your periods before the $row['rec_date']
echo "<td class='mid'><a href ="http://www.abc.co.uk/edit2.php?ident=".$row['id']."">". $row['rec_date']."</a></td></tr>";
2
u/LoudAd1396 May 21 '25
You're missing a quotation mark in your last bit.
Personally I prefer printf for cleanliness:
$variable = 'value'; Printf(' my variable goes here: %s', $variable); // my variable goes here: value
-1
u/isoAntti May 21 '25
use some linefeeds to your advantage: