What are the best practices for storing user data in a MySQL database using PHP?

When storing user data in a MySQL database using PHP, it is important to follow best practices to ensure security and efficiency. This includes sanitizing user input to prevent SQL injection attacks, using prepared statements to prevent SQL injection and improve performance, and hashing sensitive data like passwords before storing them in the database.

// Example of storing user data in a MySQL database using PHP

// Connect to MySQL database
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

// Sanitize user input
$username = $mysqli->real_escape_string($_POST['username']);
$email = $mysqli->real_escape_string($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

// Prepare SQL statement
$stmt = $mysqli->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $email, $password);

// Execute SQL statement
$stmt->execute();

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