What is the best practice for displaying text from a MySQL table with varying lengths in PHP?
When displaying text from a MySQL table with varying lengths in PHP, it is best to truncate the text to a certain length and add ellipsis (...) at the end to indicate that the text has been shortened. This ensures that the text is displayed consistently and does not disrupt the layout of the page.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch text from MySQL table
$query = "SELECT text_column FROM table_name";
$result = mysqli_query($connection, $query);
// Display truncated text with ellipsis
while ($row = mysqli_fetch_assoc($result)) {
$truncated_text = strlen($row['text_column']) > 50 ? substr($row['text_column'], 0, 50) . '...' : $row['text_column'];
echo $truncated_text . "<br>";
}
// Close database connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What are some recommended resources for learning about object-oriented programming in PHP for beginners?
- What is the best practice for defining variables in PHP to be used in multiple functions and updated values?
- How can PHP developers efficiently generate a range of dates using DateInterval and DatePeriod objects in PHP for date selection in forms?