What are best practices for handling MySQL database connections in PHP scripts?
When working with MySQL database connections in PHP scripts, it is important to follow best practices to ensure efficient and secure handling of connections. One common approach is to use PDO (PHP Data Objects) for database connections, as it provides a secure and consistent way to interact with databases. Additionally, it is recommended to use prepared statements to prevent SQL injection attacks and properly close database connections after use to free up resources.
// Establish a PDO connection to the MySQL database
$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());
}
// Example of using a prepared statement to query the database
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
// Close the database connection
$pdo = null;