What are best practices for creating and inserting data into MySQL tables using PHP?

When creating and inserting data into MySQL tables using PHP, it is important to follow best practices to ensure data integrity and security. This includes using prepared statements to prevent SQL injection attacks, validating user input to prevent errors, and properly sanitizing data before inserting it into the database.

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

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

// Set the values for the parameters and execute the statement
$value1 = "value1";
$value2 = "value2";
$stmt->execute();

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