What are the best practices for handling data insertion and updates in a MySQL database using PHP scripts?

When inserting or updating data in a MySQL database using PHP scripts, it is important to sanitize user input to prevent SQL injection attacks. Additionally, using prepared statements can help improve performance and security by separating SQL logic from user input. It is also recommended to handle errors gracefully to provide feedback to users in case of any issues.

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

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

// Prepare and execute SQL statement for data insertion
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();

// Handle errors
if ($stmt->affected_rows > 0) {
    echo "Data inserted successfully";
} else {
    echo "Error: " . $conn->error;
}

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