What are the advantages and disadvantages of embedding SQL queries directly into PHP files versus encapsulating them within functions?
Embedding SQL queries directly into PHP files can make the code harder to maintain and debug, as the queries are scattered throughout the code. On the other hand, encapsulating SQL queries within functions can make the code more organized and easier to manage. It also promotes code reusability and helps in preventing SQL injection attacks.
// Encapsulating SQL queries within functions
function get_user_data($user_id) {
$conn = new mysqli("localhost", "username", "password", "dbname");
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$user_data = $result->fetch_assoc();
$stmt->close();
$conn->close();
return $user_data;
}
$user_id = 1;
$user_data = get_user_data($user_id);
print_r($user_data);