How can one ensure proper connection and variable values when executing an INSERT query in PHP?

To ensure proper connection and variable values when executing an INSERT query in PHP, it is important to establish a database connection using the correct credentials and sanitize user input to prevent SQL injection attacks. Additionally, make sure to properly bind parameters to the query to avoid errors and ensure that the values are inserted correctly into the database.

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

// Prepare and bind the INSERT statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

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

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