What are the best practices for handling database connections in PHP when setting SQL variables?

When setting SQL variables in PHP, it's important to properly handle database connections to avoid potential security vulnerabilities and performance issues. One best practice is to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, using a connection pooling mechanism can help improve performance by reusing existing connections rather than creating new ones for each query.

// Establish a database connection using PDO
$dsn = "mysql:host=localhost;dbname=mydatabase";
$username = "username";
$password = "password";

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");

// Bind a value to the parameter
$id = 1;
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

// Execute the statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Close the database connection
$pdo = null;