What are the best practices for structuring PHP code to ensure efficient and accurate data output from a MySQL database?
To ensure efficient and accurate data output from a MySQL database in PHP, it is important to properly structure the code by using functions to handle database connections, queries, and data retrieval. This helps in keeping the code organized, reusable, and easy to maintain. Additionally, using prepared statements can help prevent SQL injection attacks and improve performance by reducing the need for repetitive query parsing.
// Function to establish a database connection
function connectToDatabase() {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
// Function to execute a query
function executeQuery($conn, $sql) {
$result = $conn->query($sql);
if (!$result) {
die("Error executing query: " . $conn->error);
}
return $result;
}
// Function to retrieve data from a query result
function fetchData($result) {
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
// Example of using the functions to retrieve data from a database
$conn = connectToDatabase();
$sql = "SELECT * FROM table";
$result = executeQuery($conn, $sql);
$data = fetchData($result);
// Output the data
foreach ($data as $row) {
echo $row['column_name'] . "<br>";
}
// Close the database connection
$conn->close();