What are the potential security risks of accessing external databases or websites in PHP scripts?

Accessing external databases or websites in PHP scripts can pose security risks such as SQL injection, cross-site scripting (XSS), and data leakage. To mitigate these risks, it is important to sanitize user input, use parameterized queries for database interactions, and validate and escape data before displaying it on a webpage.

// Example of using parameterized queries to access an external database safely

// Initialize database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare and bind SQL statement with parameters
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);

// Set and execute query parameters
$id = 1;
$stmt->execute();

// Get result set
$result = $stmt->get_result();

// Process result set
while ($row = $result->fetch_assoc()) {
    // Output data
    echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
}

// Close statement and connection
$stmt->close();
$conn->close();