What best practice should be followed when inserting new data into a database table in PHP?

When inserting new data into a database table in PHP, it is important to use prepared statements to prevent SQL injection attacks. Prepared statements separate SQL logic from user input, making it safer to insert data into the database. This practice helps to sanitize user input and ensures that malicious SQL queries cannot be executed.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");

// Bind parameters to the placeholders
$stmt->bindParam(':value1', $value1);
$stmt->bindParam(':value2', $value2);

// Set the values of the parameters
$value1 = 'example1';
$value2 = 'example2';

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