What best practices should be followed when handling database connections and queries in separate PHP files for better code organization and maintenance?
When handling database connections and queries in separate PHP files for better code organization and maintenance, it is recommended to create separate files for database connection and query functions. This separation helps in modularizing the code and makes it easier to maintain and debug. Additionally, using functions for common database operations can help in reusability and readability of the code.
// db_connect.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
// db_queries.php
<?php
include 'db_connect.php';
function get_users() {
global $conn;
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
return $result->fetch_all(MYSQLI_ASSOC);
} else {
return [];
}
}
function add_user($name, $email) {
global $conn;
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
return true;
} else {
return false;
}
}
?>
Related Questions
- What are some best practices for structuring PHP code to separate HTML and PHP, especially when dealing with login forms and error messages?
- What are the advantages and disadvantages of using the imagepng() function in PHP for saving images?
- What are best practices for including external files in PHP scripts and ensuring their proper execution?