What are some best practices for securely handling user data in a MySQL database using PHP?

When handling user data in a MySQL database using PHP, it is important to follow best practices to ensure the security and integrity of the data. This includes using parameterized queries to prevent SQL injection attacks, encrypting sensitive data before storing it in the database, and validating user input to prevent malicious input.

// Example of securely handling user data in a MySQL database using PHP

// Establish a connection to the MySQL database
$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 a parameterized query to insert user data into the database
$stmt = $conn->prepare("INSERT INTO users (username, password) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $password);

// Encrypt sensitive data before storing it in the database
$username = encrypt($_POST['username']);
$password = encrypt($_POST['password']);

// Validate user input to prevent malicious input
if (strlen($username) > 50 || strlen($password) > 50) {
    die("Input too long");
}

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

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