What is the recommended method for inserting data into a database using PHP?

To insert data into a database using PHP, the recommended method is to use prepared statements with parameterized queries. This helps prevent SQL injection attacks and ensures data integrity. By binding parameters to placeholders in the query, you can safely insert user input into the database.

// Establish a database connection (replace 'host', 'username', 'password', and 'database' with your own values)
$connection = new mysqli('host', 'username', 'password', 'database');

// Prepare a SQL statement with a parameterized query
$stmt = $connection->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");

// Bind parameters to placeholders
$stmt->bind_param("ss", $value1, $value2);

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

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

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