What are some best practices for creating a user list/table in PHP with MySQL database integration?

When creating a user list/table in PHP with MySQL database integration, it is important to follow best practices to ensure security and efficiency. One key practice is to sanitize user input to prevent SQL injection attacks. Another practice is to use prepared statements to safely execute SQL queries. Additionally, it is recommended to validate user input before inserting it into the database to maintain data integrity.

// Connect to 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);
}

// Sanitize user input
$username = mysqli_real_escape_string($conn, $_POST['username']);
$email = mysqli_real_escape_string($conn, $_POST['email']);

// Prepare and execute SQL query
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);

if ($stmt->execute()) {
    echo "User added successfully";
} else {
    echo "Error adding user: " . $conn->error;
}

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