Is it better to store cart content in a database or use SESSION for temporary storage in PHP applications?
Storing cart content in a database is generally a better option for long-term storage and scalability, as it allows for easier retrieval and management of data. However, using SESSION for temporary storage can be more suitable for smaller applications or when real-time updates are not necessary.
// Storing cart content in a database
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "cart_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Insert cart content into the database
$product_id = $_POST['product_id'];
$quantity = $_POST['quantity'];
$sql = "INSERT INTO cart (product_id, quantity) VALUES ('$product_id', '$quantity')";
$conn->query($sql);
// Retrieve cart content from the database
$sql = "SELECT * FROM cart";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "Product ID: " . $row['product_id'] . ", Quantity: " . $row['quantity'] . "<br>";
}
$conn->close();