What are the best practices for handling database connections and queries in PHP, especially in the context of session variables?
When handling database connections and queries in PHP, it is important to open and close connections properly to avoid resource leaks. Additionally, it is recommended to use prepared statements to prevent SQL injection attacks. When dealing with session variables, make sure to sanitize any user input before using it in database queries to prevent security vulnerabilities.
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare and execute a query using a prepared statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
$username = $_SESSION['username'];
$stmt->execute();
$result = $stmt->get_result();
// Process the query results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the connection
$stmt->close();
$conn->close();