What are the best practices for organizing and structuring database queries in PHP to avoid complex and inefficient code?
When organizing and structuring database queries in PHP, it is important to avoid complex and inefficient code by following best practices such as using prepared statements to prevent SQL injection attacks, separating database logic from presentation logic, and using functions or classes to encapsulate query logic for reusability and maintainability.
// Example of organizing and structuring database queries in PHP using prepared statements and functions
// Function to connect to the database
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 fetch data from the database using a prepared statement
function fetchDataFromDatabase($conn, $id) {
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $result;
}
// Connect to the database
$conn = connectToDatabase();
// Fetch data from the database
$data = fetchDataFromDatabase($conn, 1);
// Close the database connection
$conn->close();
// Use the fetched data
echo json_encode($data);