What are the best practices for securely connecting to a MySQL database in PHP applications to retrieve and manipulate data?

To securely connect to a MySQL database in PHP applications, it is important to use prepared statements to prevent SQL injection attacks. Additionally, using PDO (PHP Data Objects) with parameterized queries can help protect against malicious input and ensure secure data retrieval and manipulation.

// Establish a secure connection to the MySQL database using PDO
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}