What is the best practice for inserting session data directly into a database in PHP?

When inserting session data directly into a database in PHP, it is important to sanitize the data to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. This helps to separate the data from the query, ensuring that the data is treated as data and not as SQL commands.

// 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 session_data (session_id, data) VALUES (:session_id, :data)");

// Bind the session data to the placeholders
$stmt->bindParam(':session_id', $_SESSION['session_id']);
$stmt->bindParam(':data', $_SESSION['data']);

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