What are the best practices for handling variables in PHP when inserting them into a database?

When inserting variables into a database in PHP, it is important to properly sanitize and escape the variables to prevent SQL injection attacks. One common way to do this is by using prepared statements with parameterized queries. This helps to separate the data from the query and ensures that the variables are treated as data rather than executable code.

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

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

// Bind the variables to the parameters in the query
$stmt->bindParam(':value1', $variable1);
$stmt->bindParam(':value2', $variable2);

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