Are there any specific recommendations for structuring PHP scripts that interact with databases to ensure compatibility across different hosting environments?
When writing PHP scripts that interact with databases, it's important to use PDO (PHP Data Objects) for database access. PDO provides a consistent interface for accessing different types of databases, ensuring compatibility across different hosting environments. Additionally, it's recommended to avoid using direct SQL queries in your code and instead use prepared statements to prevent SQL injection attacks.
// Connect to the database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$db = new PDO($dsn, $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
// Use prepared statements to interact with the database
$stmt = $db->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);