What are some best practices for organizing and displaying data from a MySQL database in a PHP script?
When organizing and displaying data from a MySQL database in a PHP script, it is important to use proper coding practices to ensure efficiency and readability. One best practice is to separate your database logic from your presentation logic by using functions or classes to handle database queries and data manipulation. Additionally, consider using prepared statements to prevent SQL injection attacks and sanitize user input before executing queries. Finally, use HTML and CSS to format and style the data for a user-friendly display.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query database for data
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
// Display data in HTML table
if ($result->num_rows > 0) {
echo "<table>";
echo "<tr><th>Column 1</th><th>Column 2</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["column1"]."</td><td>".$row["column2"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close database connection
$conn->close();
?>
Related Questions
- What role does proper syntax, such as including opening and closing PHP tags, play in preventing errors like "Parse error: syntax error"?
- What potential issues can arise when trying to split a string into two parts based on a tab character, especially when dealing with HTML content in the string?
- How can the include_path in the php.ini file be adjusted to resolve the issue?