What best practices should be followed when creating SQL queries for user registration in PHP?

When creating SQL queries for user registration in PHP, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to execute queries. Additionally, it is recommended to validate and sanitize user input before inserting it into the database to ensure data integrity.

// Assume $conn is the database connection object

// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);

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

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

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