What is the best practice for securely passing SQL query results to session variables in PHP?
To securely pass SQL query results to session variables in PHP, it is important to properly sanitize and validate the data before storing it in the session. This helps prevent SQL injection attacks and ensures that only safe data is stored in the session variables. One way to achieve this is by using prepared statements to fetch data from the database and then storing the sanitized data in session variables.
// Assume $conn is the database connection object
// Prepare and execute the SQL query
$stmt = $conn->prepare("SELECT column1, column2 FROM table WHERE condition = ?");
$stmt->bind_param("s", $condition);
$stmt->execute();
$result = $stmt->get_result();
// Fetch the data and store in session variables
if ($row = $result->fetch_assoc()) {
$_SESSION['data1'] = htmlspecialchars($row['column1']);
$_SESSION['data2'] = htmlspecialchars($row['column2']);
}
// Close the statement
$stmt->close();
Related Questions
- How can PHP be utilized to handle and process user input from a URL in a secure and efficient manner for database operations?
- What best practices should be followed when using PHP for pagination of database results?
- What could be the potential reasons for a PHP script displaying a blank screen after upgrading to PHP 7.4?