What are the best practices for inserting data into a table using PHP?

When inserting data into a table using PHP, it is important to sanitize user input to prevent SQL injection attacks. This can be done using prepared statements with parameterized queries. Additionally, error handling should be implemented to catch any potential issues during the insertion process.

// Establish a database connection
$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);
}

// Prepare and bind the SQL statement
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Set the values to be inserted
$value1 = "value1";
$value2 = "value2";

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

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