What are some best practices for inserting data into a MySQL database table using PHP?

When inserting data into a MySQL database table using PHP, it is important to properly sanitize user input to prevent SQL injection attacks. One common method is to use prepared statements with parameterized queries to securely insert data into the database.

// 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 and bind the SQL statement with parameters
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
$stmt->bind_param("ss", $value1, $value2);

// Set the parameter values
$value1 = "value1";
$value2 = "value2";

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

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