PHP生成表格添加带href的查看按钮时遇语法错误求助
Hey there! Great news—you absolutely can add <a> tags with href attributes inside table cells in your PHP-generated HTML. The error you're seeing is just from mismatched quotes and messy string concatenation in your code. Let's break down what went wrong and fix it.
What Caused the Error?
Looking at your code, there are two main issues:
- Mismatched single quotes: You're wrapping your HTML string in single quotes, but you also used single quotes for HTML attributes (like
href='...'), which confuses PHP's parser. - Extra/misplaced quotes: There's an unnecessary single quote right after
<td>and an extra trailing single quote in your<i>tag'sstyleattribute.
Corrected Code
Here's the fixed version of your loop:
while($row = mysqli_fetch_array($result)) { $output .= ' <tr> <td>'.$row["name"].'</td> <td>'.$row["temperature"].'</td> <td>'.$row["phoneno"].'</td> <td> <a href="read.php?id='. $row['id'] .'" title="View Record" data-toggle="tooltip"> <i class="fa fa-eye" style="font-size:30px; color: black;"></i> </a> </td> </tr>'; } echo $output;
Key Changes Made:
- Replaced single quotes in HTML attributes (like
href='') with double quotes (href=""), so they don't conflict with the outer single quotes wrapping the PHP string. - Removed the extra single quote right after
<td>that was breaking the string. - Fixed the
<i>tag by removing the trailing single quote in thestyleattribute (it had an extra''at the end).
Alternative Approach (Cleaner String Concatenation)
If you want to avoid mixing quotes entirely, you can use PHP's double-quoted string interpolation for a cleaner look:
while($row = mysqli_fetch_array($result)) { $output .= " <tr> <td>{$row["name"]}</td> <td>{$row["temperature"]}</td> <td>{$row["phoneno"]}</td> <td> <a href='read.php?id={$row['id']}' title='View Record' data-toggle='tooltip'> <i class='fa fa-eye' style='font-size:30px; color: black;'></i> </a> </td> </tr>"; } echo $output;
Here, we wrap the entire HTML string in double quotes, so we can use single quotes for HTML attributes and interpolate the $row values directly with curly braces.
Either approach will resolve your syntax error and render the view button correctly in your table.
内容的提问来源于stack exchange,提问作者Renzo

